匹配session
1 package dl.zhang.test.util; 2 3 import java.io.IOException; 4 import java.io.Reader; 5 import org.apache.ibatis.io.Resources; 6 import org.apache.ibatis.session.SqlSession; 7 import org.apache.ibatis.session.SqlSessionFactory; 8 import org.apache.ibatis.session.SqlSessionFactoryBuilder; 9 10 public class SessionUtil { 11 12 private static ThreadLocal<SqlSession> th_session = new ThreadLocal<SqlSession>(); 13 14 private static SqlSessionFactory ssf = null; 15 16 static { 17 try { 18 //mybatis.cfg.xml是核心配置的名字要根据自己核心配置名字去填写 19 Reader reader = Resources.getResourceAsReader("mybatis.cfg.xml"); 20 21 ssf = new SqlSessionFactoryBuilder().build(reader); 22 23 } catch (IOException e) { 24 25 e.printStackTrace(); 26 } 27 } 28 29 public static SqlSession getCurrentSession() { 30 SqlSession session = th_session.get(); 31 if (session == null) { 32 session = ssf.openSession(); 33 th_session.set(session); 34 } 35 return session; 36 } 37 38 public static void closeSession() { 39 SqlSession session = th_session.get(); 40 if (session != null) { 41 session.close(); 42 th_session.set(null); 43 } 44 45 } 46 }