Mybatis—学习过程—基础回顾Dao层开发方式回顾
1.传统开发模式
- 编写UserDao接口
public interface UserDao { List<User> findAll() throws IOException; }
- 编写UserDaoImpl实现类
public class UserDaoImpl implements UserDao { public List<User> findAll() throws IOException { InputStream resourceAsStream =Resources.getResourceAsStream("SqlMapConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream); SqlSession sqlSession = sqlSessionFactory.openSession(); List<User> userList = sqlSession.selectList("userMapper.findAll"); sqlSession.close(); return userList; } }
- 编写测试类
@Test public void testTraditionDao() throws IOException { UserDao userDao = new UserDaoImpl(); List<User> all = userDao.findAll(); System.out.println(all); }
2.代理开发模式主流
-
代理开发模式在持久层只需要写持久层接口即可,不需要手动编写实现类了
-
不需要手动编写实现类了怎么去执行的sql实现效果的?其实在执行过程中会对持久层接口使用JDK动态代理,残生一个代理对象,由代理对象实现
实现类中的操作
-
持久层接口需要遵循的规范
编写持久层接口
编写UserDao接口public interface UserDao { List<User> findAll() throws IOException; }
编写UserDao接口对应的xml文件
<mapper namespace="com.lagou.Dao.UserDao"> <!-- namespace:名称空间:与id组成SQL的唯一表示 resultType:返回值类型 --> <select id="findAll" resultType="com.lagou.pojo.User"> select * from user </select> </mapper>
测试代码
@Test public void test6() throws IOException { InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream); SqlSession sqlSession = sqlSessionFactory.openSession(); /** * sqlSession.getMapper(Class<T> var1):先获取到接口的代理对象 */ UserDao mapper = sqlSession.getMapper(UserDao.class); List<User> all = mapper.findAll(); for (User user : all) { System.out.println(user); } }