---
title: "iBATIS3中管理SqlSession类"
author: "lzstone"
date: "2010-05-26T14:36:47Z"
tags: ["XML", "配置管理"]
categories: ["企业架构"]
slug: "ibatis3-sqlsession"
draft: false
lastmod: "2010-05-26T14:39:57Z"
id: 675924
url: "https://lzstone.iteye.com/blog/675924"
---

public class IbatisSessionFactory {

      //配置文件  
    private static String CONFIG\_FILE\_LOCATION = "SqlMapper.xml";

      //ThreadLocal存放当前线程中的SqlSession  
    private static final ThreadLocal&lt;SqlSession&gt; threadLocal = new ThreadLocal&lt;SqlSession&gt;();  
    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;  
    }  
}