1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
package top.l50.work5.utils;
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;
public class SqlSessionUtil {
private static volatile SqlSessionFactory sqlSessionFactory;
// 私有构造方法,防止外部实例化
private SqlSessionUtil() {}
// 单例模式获取 SqlSessionFactory 实例
public static SqlSessionFactory getSqlSessionFactory() {
if (sqlSessionFactory == null) {
synchronized (SqlSessionUtil.class) {
if (sqlSessionFactory == null) {
try (InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml")) {
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
// 更具体的错误处理
throw new RuntimeException("Failed to create SqlSessionFactory: " + e.getMessage(), e);
}
}
}
}
return sqlSessionFactory;
}
// 获取 SqlSession 实例
public static SqlSession getSqlSession() {
return getSqlSessionFactory().openSession(true);
}
}
|