mybatis动态代理
我们之前写StudentDao的实现类的时候,很多实现方法都是大同小异的,所以就导致代码重复度很高,所以我们可以偷懒不写哈哈哈,让mybatis自动去给我们生成这个类,我们只需要写一个接口就可以了
关于动态代理,大家可以移步我这篇博客: 动态代理
在mybatis里,动态代理大概是这样的:
没使用动态代理之前:
- 首先我们把sql语句都写在mapper中
- 刚开始我们在测试类中会去创建studentDaoImpl对象,然后去调用其中的方法,然后StudentDaoImpl类中的方法再去mapper中调用对应的sql语句.
使用动态代理之后:
我们就不用写接口的实现类了,交给mybatis去创建实现类对象(这就叫动态代理对象
)
- 测试类直接操作mybatis自动创建的动态代理对象.
- 通过动态代理对象去操作mapper中的sql语句.
将之前的程序改成动态代理
StudentDao接口
@Mapper
public interface StudentDao {
void insertStudent(Student student);
}
StudentDaoMapper.xml配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace写的是接口的名称,写上之后就不用写实现类了-->
<mapper namespace="com.ctgu.dao.StudentDao">
<!--新增-->
<insert id="insertStudent" parameterType="com.ctgu.bean.Student">
insert into student(name, age, address) values(#{name}, #{age}, #{address})
</insert>
</mapper>
测试类
public class Studentdemo2Test01 {
//创建接口对象
private StudentDao studentDao;
//获取sqlSession对象
private SqlSession sqlSession;
/*
创建studentDao和sqlSession对象
*/
@Before //表示运行测试方法之前会先执行该注解的内容
public void initDao() {
sqlSession = MybatisUtil.getSqlSession();
//由mybatis创建动态代理对象,括号中的参数为被代理的接口对象
//没有这条语句的话,接口对象是没有实例化的,是空的,肯定会报错的
studentDao = sqlSession.getMapper(StudentDao.class);
}
/**
* 使用结束后关闭sqlSession
*/
@After
public void closeSession() {
if (sqlSession != null) {
sqlSession.close();
}
}
@Test
public void insertStudent() {
Student student = new Student("stu",22,"宜昌");
studentDao.insertStudent(student);
}
}