mybatis_4

mybatis动态代理

我们之前写StudentDao的实现类的时候,很多实现方法都是大同小异的,所以就导致代码重复度很高,所以我们可以偷懒不写哈哈哈,让mybatis自动去给我们生成这个类,我们只需要写一个接口就可以了

关于动态代理,大家可以移步我这篇博客: 动态代理

在mybatis里,动态代理大概是这样的:

没使用动态代理之前:

  1. 首先我们把sql语句都写在mapper中
  2. 刚开始我们在测试类中会去创建studentDaoImpl对象,然后去调用其中的方法,然后StudentDaoImpl类中的方法再去mapper中调用对应的sql语句.

使用动态代理之后:
我们就不用写接口的实现类了,交给mybatis去创建实现类对象(这就叫动态代理对象)

  1. 测试类直接操作mybatis自动创建的动态代理对象.
  2. 通过动态代理对象去操作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);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值