动态代理: 使用SqlSession.getMapper(dao接口.class) 获取这个dao接口的对象
03.1.1 步骤
(1) 去掉 Dao 接口实现类

(2)创建dao接口
package com.zsz.dao;
import com.zsz.domain.Student;
import java.util.List;
public interface StudentDao {
List<Student> selectStudents();
int insertStudent (Student student);
}
(3)创建mapper.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">
<mapper namespace="com.zsz.dao.StudentDao">
<select id="selectStudents" resultType="com.zsz.domain.Student">
<!--要执行的 sql 语句-->
select id,name,email,age from student order by id
</select>
<insert id="insertStudent">
insert into student values (#{id},#{name},#{email},#{age})
</insert>
</mapper>
(4) getMapper 获取代理对象
StudentDao studentDao = MyBatisUtil.getSqlSession().getMapper(StudentDao.class);
使用 Dao 代理对象方法执行 sql 语句
package com.zsz;
import com.zsz.Util.MybatisUtils;
import com.zsz.dao.StudentDao;
import com.zsz.domain.Student;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class TestMybatis {
@Test
public void testSelectStudents(){
/**
* 使用mybatis的动态代理的机制,使用SqlSession.getMapper(dao接口);
* getMapper能获取dao接口对应的实现类对象。
*/
SqlSession sqlSession= MybatisUtils.getSqlSession();
StudentDao dao=sqlSession.getMapper(StudentDao.class);
//com.sun.proxy.$Proxy2 : jdk的动态代理
System.out.println("dao="+dao.getClass().getName());
//调用dao的方法来执行数据库的操作
List<Student> studentList = dao.selectStudents();
for (Student student:studentList) {
System.out.println("学生"+student);
}
}
@Test
public void testInsertStudent(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
StudentDao dao = sqlSession.getMapper(StudentDao.class);
Student student=new Student();
student.setId(7);
student.setName("赵六");
student.setEmail("@qq333");
student.setAge(20);
int nums=dao.insertStudent(student);
sqlSession.commit();
System.out.println("添加对象的数量="+nums);
}
}
本文介绍如何通过MyBatis的动态代理机制实现DAO接口,包括创建DAO接口、配置mapper.xml文件、使用SqlSession获取代理对象并执行SQL语句。
1060

被折叠的 条评论
为什么被折叠?



