首页 > 代码库 > MyBatisUtil
MyBatisUtil
package 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 {
//保存不同线程的SqlSession对象
private static ThreadLocal<SqlSession> tl = new ThreadLocal<SqlSession>();
private static SqlSessionFactory sf;
//静态初始化块,初始化SqlSessionFactory
static{
String resource = "mybatis-config.xml";
Reader reader=null;
try {
reader = Resources.getResourceAsReader(resource);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sf = new SqlSessionFactoryBuilder().build(reader);
}
//获得SqlSession
public static SqlSession get(){
//从ThreadLocal对象里面取出来
SqlSession sqlSession = tl.get();
//判断sqlSession是否为空
if(sqlSession==null){
//通过sf打开一个session
sqlSession=sf.openSession();
//把该session存入到tl中
tl.set(sqlSession);
}
return sqlSession;
}
//关闭session
public static void close(){
//从ThreadLocal对象里面取session出来
SqlSession sqlSession = tl.get();
//如果sqlSession不是空,则关闭
if(sqlSession!=null){
sqlSession.close();
tl.set(null);
}
}
}
MyBatisUtil