SqlSessionFactory
是 MyBatis 框架中最核心的接口之一,它负责创建 SqlSession
对象。下面详细解析这个对象及其使用方法。
1. SqlSessionFactory 的作用
SqlSessionFactory
是 MyBatis 的工厂对象,主要职责:
- 创建
SqlSession
实例(数据库会话) - 管理数据库连接和配置信息
- 缓存已解析的映射文件
2. 创建 SqlSessionFactory 的方式
方式一:通过 XML 配置文件(最常用)
java
// 基于 mybatis-config.xml 创建
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
对应的 mybatis-config.xml
配置文件:
xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis_test"/>
<property name="username" value="root"/>
<property name="password" value="password"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>
方式二:通过 Java 代码(编程式配置)
java
// 创建数据源
DataSource dataSource = new PooledDataSource(
"com.mysql.cj.jdbc.Driver",
"jdbc:mysql://localhost:3306/mybatis_test",
"root",
"password"
);
// 配置事务工厂
TransactionFactory transactionFactory = new JdbcTransactionFactory();
// 创建环境
Environment environment = new Environment("development", transactionFactory, dataSource);
// 构建配置
Configuration configuration = new Configuration(environment);
configuration.addMapper(UserMapper.class);
// 创建 SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
方式三:在 Spring Boot 中自动配置
java
@Configuration
@MapperScan("com.example.mapper")
public class MyBatisConfig {
// Spring Boot 会自动配置 SqlSessionFactory
// 只需要在 application.properties 中配置数据源
}
application.properties
:
properties
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_test
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.example.entity
3. SqlSessionFactory 的核心方法
3.1 创建 SqlSession 的方法
java
SqlSessionFactory sqlSessionFactory = ...; // 已创建的工厂实例
// 1. 创建默认的 SqlSession(需要手动提交事务)
SqlSession sqlSession = sqlSessionFactory.openSession();
// 2. 创建自动提交的 SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession(true);
// 3. 从特定连接创建 SqlSession
Connection connection = dataSource.getConnection();
SqlSession sqlSession = sqlSessionFactory.openSession(connection);
// 4. 指定事务隔离级别
SqlSession sqlSession = sqlSessionFactory.openSession(TransactionIsolationLevel.READ_COMMITTED);
// 5. 指定执行器类型
SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
3.2 获取配置信息
java
Configuration configuration = sqlSessionFactory.getConfiguration();
// 获取所有已注册的Mapper
Collection<Class<?>> mapperClasses = configuration.getMapperRegistry().getMappers();
// 检查是否包含特定Mapper
boolean hasMapper = configuration.hasMapper(UserMapper.class);
4. SqlSessionFactory 的生命周期管理
单例模式(推荐)
java
public class MyBatisUtil {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
throw new RuntimeException("初始化SqlSessionFactory失败", e);
}
}
public static SqlSessionFactory getSqlSessionFactory() {
return sqlSessionFactory;
}
public static SqlSession openSession() {
return sqlSessionFactory.openSession();
}
}
5. 完整使用示例
实体类和Mapper接口
java
// 实体类
public class User {
private Long id;
private String name;
private String email;
// getter/setter
}
// Mapper接口
public interface UserMapper {
User selectUserById(Long id);
void insertUser(User user);
void updateUser(User user);
void deleteUser(Long id);
}
Mapper XML 文件
xml
<!-- UserMapper.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.example.mapper.UserMapper">
<select id="selectUserById" parameterType="long" resultType="User">
SELECT * FROM user WHERE id = #{id}
</select>
<insert id="insertUser" parameterType="User">
INSERT INTO user (name, email) VALUES (#{name}, #{email})
</insert>
</mapper>
使用 SqlSessionFactory 执行操作
java
public class UserService {
public User getUserById(Long id) {
// 获取 SqlSessionFactory(单例)
SqlSessionFactory sqlSessionFactory = MyBatisUtil.getSqlSessionFactory();
// 创建 SqlSession
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
// 方式一:通过Mapper接口(推荐)
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.selectUserById(id);
// 方式二:通过命名空间直接调用(不推荐)
// User user = sqlSession.selectOne("com.example.mapper.UserMapper.selectUserById", id);
return user;
} // 自动关闭SqlSession
}
public void addUser(User user) {
SqlSessionFactory sqlSessionFactory = MyBatisUtil.getSqlSessionFactory();
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
userMapper.insertUser(user);
sqlSession.commit(); // 手动提交事务
}
}
}
6. 最佳实践
- 单例模式 :在整个应用生命周期中只创建一个
SqlSessionFactory
实例 - 资源管理 :使用 try-with-resources 确保
SqlSession
正确关闭 - 事务管理:根据业务需求选择合适的提交方式
- 连接池配置:在生产环境中使用连接池提高性能
- 配置文件外部化:将数据库配置放在外部文件中,便于环境切换
7. 常见配置项
在 mybatis-config.xml
中的常用配置:
xml
<configuration>
<settings>
<!-- 开启缓存 -->
<setting name="cacheEnabled" value="true"/>
<!-- 开启延迟加载 -->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 数据库字段下划线转驼峰 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<typeAliases>
<package name="com.example.entity"/>
</typeAliases>
</configuration>
SqlSessionFactory
是 MyBatis 的入口点,正确创建和管理这个对象是使用 MyBatis 的基础。掌握它的创建方式和使用方法,能够帮助你更好地构建 MyBatis 应用程序。