首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

iBATIS3中治理SqlSession类

2012-10-08 
iBATIS3中管理SqlSession类public class IbatisSessionFactory {????? //配置文件??? private static Stri

iBATIS3中管理SqlSession类

public class IbatisSessionFactory {

????? //配置文件
??? private static String CONFIG_FILE_LOCATION = "SqlMapper.xml";

????? //ThreadLocal存放当前线程中的SqlSession
??? private static final ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
??? private static SqlSessionFactory sessionFactory;
??? private IbatisSessionFactory() {
??? }
??? //获取SqlSession
??? public static SqlSession getSession() {
??? ??? SqlSession session = (SqlSession) threadLocal.get();

??? ??? if (session == null) {
??? ??? ??? if (sessionFactory == null) {
??? ??? ??? ??? rebuildSessionFactory();
??? ??? ??? }
??? ??? ??? session = (sessionFactory != null) ? sessionFactory.openSession()
??? ??? ??? ??? ??? : null;
??? ??? ??? threadLocal.set(session);
??? ??? }

??? ??? return session;
??? }
??? //构建SessionFactory
??? public static void rebuildSessionFactory() {
??? ??? try {
??? ??? ??? Reader reader = Resources.getResourceAsReader(CONFIG_FILE_LOCATION);
??? ??? ??? sessionFactory = new SqlSessionFactoryBuilder().build(reader);
??? ??? } catch (IOException e) {
??? ??? ??? e.printStackTrace();
??? ??? }
??? }
??? //关闭SqlSession
??? public static void closeSession() {
??? ??? SqlSession session = (SqlSession) threadLocal.get();
??? ??? threadLocal.set(null);

??? ??? if (session != null) {
??? ??? ??? session.close();
??? ??? }
??? }
??? //将SessionFactory关闭
??? public static void closeSessionFactory() {
??? ??? sessionFactory = null;
??? }
}

热点排行