package cn.bdqn.mhouse.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; /** * * * 项目名称:mhouse * 类名称:MybatisUtil * 类描述: 工具类 * 创建人:Mu Xiongxiong * 创建时间:2017-3-15 下午1:31:54 * 修改人:Mu Xiongxiong * 修改时间:2017-3-15 下午1:31:54 * 修改备注: * @version * */ public class MybatisUtil { private static SqlSessionFactory factory; private static ThreadLocal<SqlSession> sl=new ThreadLocal<SqlSession>(); private static final String RESOURCE="mybatis-config.xml"; /** * 静态初始化 */ static{ try { Reader reader=Resources.getResourceAsReader(RESOURCE); SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder(); factory=builder.build(reader); } catch (IOException e) { e.printStackTrace(); }catch (Exception e) { e.printStackTrace(); } } /** * * @Title: getSession * @Description: 该方法的主要作用:打开session * @param @return 设定文件 * @return 返回类型:SqlSession * @throws */ public static SqlSession getSession(){ SqlSession session=sl.get(); if(session==null){ session=factory.openSession(); sl.set(session); } return session; } /** * * @Title: closeSession * @Description: 该方法的主要作用:关闭session * @param 设定文件 * @return 返回类型:void * @throws */ public static void closeSession(){ SqlSession session=sl.get(); sl.set(null); if(session!=null){ session.close(); } } }