Mapping Overview
(Continued from the previous section, supplementing the remaining parts)
SqlSession Factory Builder
SqlSessionFactoryBuilder, SqlSessionFactory is one of the core components in the MyBatis framework. It is the factory that creates SqlSession objects. The construction of SqlSessionFactory is usually done through the SqlSessionFactoryBuilder class.
SqlSessionFactoryBuilder is an auxiliary class provided by MyBatis for building SqlSessionFactory. Its main task is to read MyBatis configuration information through configuration files or configuration streams and build SqlSessionFactory instances.
Since SqlSessionFactory is thread-safe and should follow the singleton pattern, we typically only need to build SqlSessionFactory once during application startup and store it for subsequent use.
Common API:
SqlSessionFactory build(InputStream inputStream);
Builds a SqlSessionFactory object by loading XML configuration
SqlSessionFactory Build Process
The main steps to build SqlSessionFactory are as follows:
Load Configuration File
Load MyBatis XML configuration file through Resources.getResourceAsStream() or Resources.getResourceAsReader().
Parse Configuration File
Use XMLConfigBuilder to parse the configuration file, converting the XML configuration file into MyBatis’s Configuration object.
Create SqlSessionFactory Instance
SqlSessionFactoryBuilder encapsulates the parsed Configuration object into a concrete SqlSessionFactory implementation class (typically DefaultSqlSessionFactory).
String resource = "org/mybatis/builder/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(inputStream);
Among them, the Resource utility class, located in the org.apache.ibatis.io package, helps you load resource files from the classpath, file system, or a web URL.
Core Features of SqlSessionFactory
Thread Safety
SqlSessionFactory is thread-safe and can be shared among multiple threads. Therefore, it is recommended to create and manage it using the singleton pattern throughout the application lifecycle.
Creating SqlSession
The main responsibility of SqlSessionFactory is to create SqlSession objects. Each thread should independently use one SqlSession instance.
Loading Configuration Information
SqlSessionFactory internally maintains all configuration information, including database connection pool, transaction manager, SQL mapping statements, etc.
SqlSessionFactory Object
In the MyBatis framework, SqlSessionFactory is a very important core object whose role is to create and manage instances of SqlSession objects. SqlSession is the main object used in MyBatis for executing SQL operations, while SqlSessionFactory is the factory that generates these SqlSessions. Through SqlSessionFactory, unified management of database sessions can be achieved, ensuring efficient resource utilization and thread safety.
SqlSessionFactory has multiple methods to create SqlSession, such as:
- openSession: By default, opens a transaction but does not auto-commit, meaning manual transaction commit is required for update operation data to persist to the database
- openSession(boolean autoCommit): Parameter determines whether to auto-commit; if set to true, manual transaction commit is not required
SqlSession Session Object
The SqlSession instance is a very powerful class in MyBatis, where you will see all methods for executing statements, committing or rolling back transactions, and obtaining mapper instances.
Main methods for executing statements:
<T> T selectOne(String statement, Object parameter)
<E> List<E> selectList(String statement, Object parameter)
int insert(String statement, Object parameter)
int update(String statement, Object parameter)
int delete(String statement, Object parameter)
Main methods for transaction operations:
void commit()
void rollback()
DAO Layer Implementation
Traditional Approach
package icu.wzk.dao;
import icu.wzk.model.UserInfo;
import java.util.List;
public interface UserInfoMapper {
UserInfo selectOne(String username);
List<UserInfo> selectList(UserInfo userInfo);
void insert(UserInfo userInfo);
void update(UserInfo userInfo);
void delete(UserInfo userInfo);
}
Proxy Approach
Method Introduction
This approach uses MyBatis’s proxy development method to implement DAO layer, which is the mainstream approach when entering enterprises later.
The Mapper interface development method only requires programmers to write the Mapper interface. The MyBatis framework creates dynamic proxy objects for the interface based on the interface definition. The proxy object’s methods are the same as the DAO interface implementation class methods mentioned above.
- Mapper XML’s namespace and the fully qualified name of the mapper interface must be the same
- Mapper interface method names must match each statement id defined in Mapper XML
- Mapper interface method input parameters must match each SQL’s parameterType type defined in Mapper XML
- Mapper interface method output parameter types must match each SQL’s resultType defined in Mapper XML
Test proxy method:
package icu.wzk;
import icu.wzk.mapper.UserInfoMapper;
import icu.wzk.model.UserInfo;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class WzkIcu05 {
public static void main(String[] args) throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserInfoMapper userInfoMapper = sqlSession.getMapper(UserInfoMapper.class);
List<UserInfo> dataList = userInfoMapper.selectList(new UserInfo());
dataList.forEach(System.out::println);
sqlSession.close();
}
}