MyBatis 工作流程
MyBatis 核心对象
- SqlSessionFactoryBuilder
SqlSession工厂构建者对象,使用构造者模式创建SqlSession工厂对象。
- SqlSessionFactory
SqlSession工厂,使用工厂模式创建SqlSession对象。
- SqlSession
该对象可以操作数据库,也可以使用动态代理模式创建持久层接口的代理对象操作数据库。
- Mapper
持久层接口的代理对象,他具体实现了持久层接口,用来操作数据库。
MyBatis 工作流程
- 创建SqlSessionFactoryBuilder对象
- SqlSessionFactoryBuilder对象构建了SqlSessionFactory对象:构造者模式
- SqlSessionFactory对象生产了SqlSession对象:工厂模式
- SqlSession对象创建了持久层接口的代理对象:动态代理模式
- 代理对象操作数据库
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();
}