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);
    }
}

这个SqlSessionUtil工具类的特色:

  1. 单例模式: 通过使用单例模式确保了在整个应用程序生命周期内只有一个 SqlSessionFactory 实例。这种设计可以减少资源消耗,并提高性能。
  2. 线程安全: 代码采用了双重检查锁定机制,保证了在多线程环境下的线程安全性。这样就可以避免多个线程同时访问时可能出现的竞态条件问题。
  3. 异常处理: 在获取 SqlSessionFactory 过程中,对可能出现的 IOException 进行了处理,并提供了更具体的错误消息。这有助于更快地定位和解决问题,提高了代码的可靠性和可维护性。
  4. 封装性: 工具类封装了 MyBatis 的初始化和资源获取过程,提供了一个便捷的方法来获取 SqlSession 实例。这样就简化了代码使用,降低了代码耦合度,使得代码更加清晰和易于理解。