MyBatis学习之动态代理机制

本文详细介绍了MyBatis的传统DAO方式实现,包括接口定义、SQL映射文件配置、接口实现类的创建以及调用过程。接着分析了使用动态代理的条件,指出动态代理机制下,MyBatis如何根据DAO方法调用来获取SQL信息并执行。最后,阐述了MyBatis动态代理的具体实现,即通过SqlSession的getMapper方法获取接口的实现类对象,简化了代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.传统dao方式实现mybatis

  • 1.定义接口
package com.xhy.dao;
import com.xhy.entity.Student;
import java.util.List;

public interface StudentDao {
    List<Student> selectStudents();
}

  • 2.定义sql映射文件
<!--namespace:命名空间,唯一值的。要求使用dao接口的全限定名称。也就是(com.xhy.dao.StudentDao)-->
<mapper namespace="com.xhy.dao.StudentDao">
<!--id:是这条sql语句的唯一标识,mybatis通过id来找到要执行的sql语句,要求使用接口中的方法名称-->
    <select id="selectStudents" resultType="com.xhy.entity.Student">
        select id,name,email,age from student order by id;
    </select>
</mapper>
  • 3.创建接口实现类,通过实现接口中的selectStudents()方法来访问mybatis实现查询
public class StudentDaoImpl implements StudentDao {
    @Override
    public List<Student> selectStudents() {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        String sqlId = "com.xhy.dao.StudentDao.selectStudents";
        List<Student> students = sqlSession.selectList(sqlId);
        sqlSession.close();
        return students;
    }
  • 4.创建接口实现类的dao对象,通过该对象调用selectStudents()方法
public void TestselectStudents(){
        StudentDao dao = new StudentDaoImpl();
        List<Student> studentList = dao.selectStudents();
        for (Student student :studentList){
            System.out.println(student);
        }
        }

二.使用动态代理的条件分析

在传统的dao方式中,我们实现mybatis查询时:

  • 1.先创建dao接口实现类的对象
StudentDao dao = new StudentDaoImpl();

说明
dao对象的的类型是:StudentDao,它的全限定名称就是:com.xhy.dao.StudentDao
它的全限定名称和namespace是一样的

  • 2.该对象调用selectStudents()方法
List<Student> studentList = dao.selectStudents();

说明
该方法名称是selectStudents,而这个方法名称就是mapper文件中的id值。

  • 也就是说dao调用方法时也是组合出了sqld(com.xhy.dao.StudentDao.selectStudents),mybatis通过该sqlId找到了要执行的sql语句并执行。

  • 并且通过dao中方法的返回值就可以确定要调用哪个sqlSession的方法:
    1.如果返回值是List,那就是调用sqlSession.selectList()方法
    2.如果返回值不是List,会根据mapper文件中的标签确定是调用update()insert()等哪个方法

三.mybatis动态代理

  • mybatis根据dao方法的调用,获取要执行的sql语句的信息
  • mybatis根据你的dao接口,创建出它的接口实现类,并创建这个类的对象
  • 完成sqlSession的方法调用,访问数据库
  • 具体实现

mybatis动态代理机制的实现:是使用SqlSession.getMapper(dao接口)
getMapper能获取dao接口对应的实现类对象

        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        //getMapper能获取dao接口对应的实现类对象
        StudentDao dao = sqlSession.getMapper(StudentDao.class);
        List<Student> studentList = dao.selectStudents();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值