`
lzstone
  • 浏览: 92640 次
  • 性别: Icon_minigender_1
  • 来自: 大连
社区版块
存档分类
最新评论

iBATIS3中管理SqlSession类

    博客分类:
  • java
阅读更多

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

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics