1 private static final ThreadLocal threadSession = new ThreadLocal(); 2 3 public static Session getSession() throws InfrastructureException { 4 Session s = (Session) threadSession.get(); 5 try { 6 if (s == null) { 7 s = getSessionFactory().openSession(); 8 threadSession.set(s); 9 } 10 } catch (HibernateException ex) { 11 throw new InfrastructureException(ex); 12 } 13 return s; 14 } 15 16 17public class ConnectionUtil { 18 private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>(); 19 private static Connection initConn = null; 20 static { 21 try { 22 initConn = DriverManager.getConnection("url, name and password"); 23 } catch (SQLException e) { 24 e.printStackTrace(); 25 } 26 } 27 28 public Connection getConn() { 29 Connection c = tl.get(); 30 if(null == c) tl.set(initConn); 31 return tl.get(); 32 } 33 34}
threadlocal
Easter79
2021-10-12
1152 1 0
点赞
收藏
评论区
加载中...