MyBatis 工作流程

MyBatis 工作流程

在这里插入图片描述

MyBatis 核心对象

  • SqlSessionFactoryBuilder

SqlSession工厂构建者对象,使用构造者模式创建SqlSession工厂对象。

  • SqlSessionFactory

SqlSession工厂,使用工厂模式创建SqlSession对象。

  • SqlSession

该对象可以操作数据库,也可以使用动态代理模式创建持久层接口的代理对象操作数据库。

  • Mapper

持久层接口的代理对象,他具体实现了持久层接口,用来操作数据库。

MyBatis 工作流程

  1. 创建SqlSessionFactoryBuilder对象
  2. SqlSessionFactoryBuilder对象构建了SqlSessionFactory对象:构造者模式
  3. SqlSessionFactory对象生产了SqlSession对象:工厂模式
  4. SqlSession对象创建了持久层接口的代理对象:动态代理模式
  5. 代理对象操作数据库

StudentDao.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.mapper.StudentMapper">
    <select id="selectStudentList" resultType="com.entity.Student">
       select * from student;
    </select>
</mapper>

Dao 层代码如下:

public interface StudentMapper {
    List<Student> selectStudentList();
}

测试代码如下:

@Test
public void testSelectStudentList() throws Exception {
    // (1)读取核心配置文件
    InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
    // (2)创建SqlSessionFactoryBuilder对象
    SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
    // (3)SqlSessionFactoryBuilder对象获取SqlSessionFactory对象
    SqlSessionFactory factory = builder.build(is);
    // (4)SqlSessionFactory对象获取SqlSession对象
    SqlSession session = factory.openSession();
    // (5)SqlSession对象获取代理对象
    UserMapper studentMapper = session.getMapper(StudentMapper.class);
    // (6)代理对象执行方法
    List<Student> list = studentMapper.selectStudentList();
    list.forEach(System.out::println);
    // (7)释放资源
    session.close();
    is.close();
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我真真的是小白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值