Dao 代理实现 CURD
3.1.1 步骤
(1) 去掉 Dao 接口实现类
(2) getMapper 获取代理对象
只需调用 SqlSession 的 getMapper()方法,即可获取指定接口的实现类对象。
该方法的参数为指定 Dao 接口类的 class 值。
SqlSession session = factory.openSession();
StudentDao dao = session.getMapper(StudentDao.class);
使用工具类:
StudentDao studentDao=MyBatisUtil.getSqlSession().getMapper(StudentDao.class)
);
(3) 使用 Dao 代理对象方法执行 sql 语句
select 方法:
@Test
public void testSelect() throws IOException {
final List studentList = studentDao.selectStudents();
studentList.forEach( stu -> System.out.println(stu));
insert 方法:
@Test
public void testInsert() throws IOException {
Student student = new Student();
student.setId(1006);
student.setName(“林浩”);
student.setEmail(“linhao@163.com”);
student.setAge(26);
int nums =studentDao.insertStudent(student);
System.out.println(“使用 Dao 添加数据:”+nums);
}
原理:动态代理