public class SqlSessionUtil {
/**
* 單例模式:1. 本類不能在外部實例化 2.單例的方法,在方法中創建本類的實例。 3. 向外公開一個靜態的方法,返回本類的實例。
*/
private SqlSessionUtil() {
}
private static Reader reader;
// 讀取主配置文件,形成一個文件流.配置文件只需要讀取一次就行了,所以寫在靜態代碼塊中
static {
try {
reader = Resources.getResourceAsReader("config/mybatis-config.xml");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
private static SqlSessionFactory factory = null;
private static Object obj = new Object();
// 單例模式的SqlSessionFactory工廠
private static SqlSessionFactory getSessionFactory() {
if (factory == null) {
synchronized (obj) { // 鎖
if (factory == null) { //
factory = new SqlSessionFactoryBuilder().build(reader);
}
}
}
return factory;
}
// 向外公開一個方法,返回SqlSession對象。
public static SqlSession getSession() {
return getSessionFactory().openSession();
}
}