版本一:
public class MyBatisUtil { private static SqlSessionFactory factory = null; static { InputStream is = null; try { is = Resources.getResourceAsStream("mybatis-config.xml"); factory = new SqlSessionFactoryBuilder().build(is); } catch (IOException e) { throw new RuntimeException("mybatis配置文件加载异常",e); }finally { if(is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } }
/** * 获得SqlSession * @throws Exception */ public static SqlSession getSqlSession() throws Exception { SqlSession session = factory.openSession(); return session; } }
版本二:
public class MyBatisUtil2 { private static SqlSessionFactory factory = null; private static ThreadLocal<SqlSession> td1 = new ThreadLocal<SqlSession>(); static { InputStream is = null; try { is = Resources.getResourceAsStream("mybatis-config.xml"); factory = new SqlSessionFactoryBuilder().build(is); } catch (IOException e) { throw new RuntimeException("mybatis配置文件加载异常",e); }finally { if(is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 获得SqlSession * @throws Exception */ public static SqlSession getSqlSession(){ //1.获得DAO对象 SqlSession SqlSession session = null; //2.从当前线程中获得session try { session = td1.get(); if(session == null) { //当前线程如果没有sqlsession,就赋值 session = factory.openSession(); //将session存入当前线程 td1.set(session); } } catch (Exception e) { throw new RuntimeException("获得sqlsession的异常",e); } return session; } /** * 根据接口的类对象,获得DAO对象 */ public static <T> T getMapper(Class<T> clazz) { //获得sqlsession SqlSession session = getSqlSession(); //调用session.getMapper(clazz); T t = session.getMapper(clazz); return t; } /** * 提交事务+释放资源 */ public static void commit() { //sqlsession.commit(); try { SqlSession session = getSqlSession(); session.commit(); } catch (RuntimeException e) { throw e; }finally { close(); } } /** * 回滚事务+释放资源 */ public static void rollback() { try { SqlSession session = getSqlSession(); session.rollback(); } catch (RuntimeException e) { throw e; }finally { //释放资源 close(); } } /** * 释放session资源 */ public static void close() { SqlSession session = getSqlSession(); if(session != null) { session.close(); //从当前线程中移除该session td1.remove(); } } }