Article directory
MyBatis workflow
MyBatis Core Objects
- SqlSessionFactoryBuilder
The SqlSession factory builder object uses the constructor pattern to create the SqlSession factory object.
- SqlSessionFactory
SqlSession factory, use factory pattern to create SqlSession object.
- SqlSession
This object can operate the database, and can also use the dynamic proxy mode to create a proxy object of the persistence layer interface to operate the database.
- Mapper
The proxy object of the persistence layer interface, which implements the persistence layer interface and is used to operate the database.
MyBatis workflow
- Create a SqlSessionFactoryBuilder object
- The SqlSessionFactoryBuilder object builds the SqlSessionFactory object: Constructor mode
- The SqlSessionFactory object produces the SqlSession object: factory mode
- The SqlSession object creates a proxy object for the persistence layer interface: dynamic proxy mode
- The proxy object operates the database
The StudentDao.xml file is as follows:
<?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>
The Dao layer code is as follows:
public interface StudentMapper {
List<Student> selectStudentList();
}
The test code is as follows:
@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();
}