package com.Util;
import java.io.IOException;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisUtil {
private MyBatisUtil() {}
/**声明静态的
* (1)ThreadLocal<org.apache.ibatis.session.SqlSession>
* (2)org.apache.ibatis.session.SqlSessionFactory
* 以保证SqlSession在线程(准确的说是一次请求)中的唯一性。
*/
private static final ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
private static SqlSessionFactory sqlSessionFactory;
/**
* (1)加载myBatis-config.xml文件
* (2)创建org.apache.ibatis.session.SqlSessionFactory对象
*/
public static void buildSqlSessionFactory() {
Reader reader=null;
try {
reader=Resources.getResourceAsReader("myBatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e) {
System.err.println("加载myBatis-config.xml文件、创建org.apache.ibatis.session.SqlSessionFactory对象失败");
e.printStackTrace();
}finally{
try {
reader.close();//关闭字符流
} catch (IOException e) {
e.printStackTrace();//输入输出异常
}
}
}
/*应用程序启动时执行*/
static {
try {
buildSqlSessionFactory();
} catch (Exception e) {
e.printStackTrace();
}
}
/**从当前线程的threadLocal中获取SqlSession,
* 判断SqlSession是否为空,
* 如果SqlSession为空,判断SqlSessionFactory是否为空,是则重建SqlSessionFactory,否则创建SqlSession对象,并放入threadLocal
* 如果SqlSession不为空,返回SqlSession
**/
public static SqlSession getSqlSession(){
SqlSession sqlSession = null;
try {
sqlSession = (SqlSession) threadLocal.get();
if (sqlSession == null) {
if (sqlSessionFactory == null) {
buildSqlSessionFactory();
}
sqlSession = (sqlSessionFactory != null) ? sqlSessionFactory
.openSession() : null;
threadLocal.set(sqlSession);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("-------------获取sqlSession失败--------------");
}
return sqlSession;
}
/**
* 关闭SqlSession
*/
public static void closeSqlSession(){
SqlSession sqlSession = (SqlSession) threadLocal.get();
threadLocal.set(null);
if (null!=sqlSession) {
sqlSession.close();
}
}
/**
*获取SqlSessionFactory
*/
public static SqlSessionFactory getSessionFactory() {
return sqlSessionFactory;
}
}
/Util/MyBatisUtil.java
最新推荐文章于 2022-07-29 23:07:26 发布