5、MyBatis传统Dao开发 & Dao动态代理开发

学习资源:动力节点《2020最新MyBatis教程【IDEA版】-MyBatis从入门到精通》



1、MyBatis 传统 Dao 开发方式

之前的 selectStudents() 是这样实现的,代码如下:

@Test
public void testStart() throws IOException {
    // 1.mybatis 主配置文件
    String config = "mybatis-config.xml";
    // 2.读取配置文件
    InputStream in = Resources.getResourceAsStream(config);
    // 3.创建 SqlSessionFactoryBuilder 对象,目的是获取 SqlSession
    SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
    // 4.创建 SqlSessionFactory 对象
    SqlSessionFactory factory = builder.build(in);
    // 5.获取 SqlSession,SqlSession 能执行 sql 语句
    SqlSession session = factory.openSession();
    // 6.指定要执行的 sql 语句的标识 = SQL映射文件中的 namespace + "." + 标签的id
    String sql = "com.bjpowernode.dao.StudentDao.selectStudents";
    // 7.执行 SqlSession 的 selectList()
    List<Student> studentList = session.selectList(sql);
    // 8.循环输出查询结果
	studentList.forEach( student -> System.out.println(student));
    // 9.关闭 SqlSession,释放资源
	session.close();
}

这种形式的代码也可以写成下面这样的形式:

public class Student {
    //属性名和列名一样
    private Integer id;
    private String name;
    private String email;
    private Integer age;
    // set ,get , toString
}

------------------------------------------------------

public interface StudentDao {
    
    // 查询所有数据
    List<Student> selectStudents();
}

------------------------------------------------------
    
public class StudentDaoImpl {
    
    public List<Student> selectStudents(){
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        String sql = "com.bjpowernode.dao.StudentDao.selectStudents";
        List<Student> students = sqlSession.selectList(sql);
        sqlSession.close;
        return students;
    }
}

------------------------------------------------------

public class testDaoImpl{

    public static void mian(String[] args){
		
        new Student
    }
}

此时,我们会发现这样的写法和传统的 JDBC 、dao接口 + DaoImpl实现类 方式并没有什么区别:那么 MyBatis 又有什么意义呢?

2、MyBatis 框架 Dao 代理

在前面例子中自定义 Dao 接口实现类时发现一个问题: Dao 的实现类其实并没有干什么实质性的工作,它仅仅就是通过 SqlSession 的相关 API 定位到映射文件 mapper 中相应 id 的 SQL 语句,真正对 DB 进行操作的工作其实是由框架通过 mapper 中的 SQL 完成的。

所以, MyBatis 框架就抛开了 Dao 的实现类,直接定位到映射文件 mapper 中的相应 SQL 语句,对 DB 进行操作。这种对 Dao 的实现方式称为 Mapper 的动态代理方式。Mapper 动态代理方式无需程序员实现 Dao 接口。接口是由 MyBatis 结合映射文件自动生成的动态代理实现的。

2.1、去掉 Dao 接口实现类

image-20200828212442703


2.2、使用 SqlSession.getMapper() 获取代理对象

只需调用 SqlSessiongetMapper() 方法,即可获取指定接口的实现类对象。该方法的参数为指定 Dao 接口类的 class 值。

获取到接口的实现类对象即可调用接口的方法/

SqlSession session = factory.openSession();
StudentDao dao = session.getMapper(StudentDao.class);

Student student = new Student();

dao.select();
dao.insert(student);

2.3、实现原理

JDK 动态代理

image-20200829204409071

MapperProxy 类定义:

image-20200829204445626

invoke()方法:

image-20200829204502140

重点方法:

image-20200829204540466

原文地址:https://www.cnblogs.com/sout-ch233/p/13608323.html