Mybatis(三)动态代理方式实现增删改查
在上一篇文章中,我们使用静态代理的方式,通过一个类来实现DAO接口从而实现增删改查;在这篇文章中,将使用动态代理的方式进行功能的实现,其原理是Java的反射机制。话不多说,先上代码为敬。
- 更改TestMybatis文件如下:
package cn.krain;
import cn.krain.dao.StudentDao;
import cn.krain.domain.Student;
import cn.krain.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class TestMybatis {
//查询功能,sqlSession执行完毕后都需要关闭
@Test
public void testSelectStudents(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
StudentDao dao = sqlSession.getMapper(StudentDao.class);
List<Student> students = dao.selectStudents();
sqlSession.close();
for (Student stu:students) {
System.out.println(stu);
}
}
//插入功能
@Test
public void testInsertStudent(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
StudentDao dao = sqlSession.getMapper(StudentDao.class);
Student student = new Student();
student.setId(7);
student.setName("花花2");
student.setEmail("8654@qq.com");
student.setAge(21);
int n = dao.insertStudent(student);
sqlSession.commit();
sqlSession.close();
System.out.println(n);
}
//更新功能
@Test
public void testUpdateStudent(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
StudentDao dao = sqlSession.getMapper(StudentDao.class);
Student student = new Student();
student.setId(7);
student.setAge(10);
int n = dao.updateStudent(student);
sqlSession.commit();
sqlSession.close();
System.out.println(n);
}
//删除功能
@Test
public void testDeleteStudent(){
SqlSession sqlSession = MybatisUtil.getSqlSession();
StudentDao dao = sqlSession.getMapper(StudentDao.class);
Student student = new Student();
student.setId(7);
int n = dao.deleteStudent(student);
sqlSession.commit();
sqlSession.close();
System.out.println(n);
}
}
在上篇文章 使用静态代理实现 的基础上,我只需要去掉实现接口的类,同时修改TestMybatis类;在TestMybatis类中,当每个方法获取DAO对象时,使用SqlSession对象中的getMapper(dao.class)方法即可。