關於hibernate session管理的一些問題

hibernate中,sessionFactory是線程安全的,可以被所有的應用程序共享,而session不是線程安全的,被多個線程共享時會出現不可預知的後果,那麼對session 採用ThreadLocal實現共享會出問題嗎?
[code]
public class HibernateUtil {
private static SessionFactory sessionFactory;
static{
try{
sessionFactory = new Configuration().configure().buildSessionFactory();
}catch(HibernateException e){
throw new RunTimeException("Configuration problem:"+e.getMessage());
}
}
public static final TreadLocal session = new ThreadLocal();
public static Session currentSession() thrwos HibernateException{
Session s = (Session) session.get();
if(s==null){
s = sessionFactory().openSession();
session.set(s);
}
return s;
}
public static void closeSession() throws HibernateException{
Session s = (Session)session.get();
session.set(null);
if(null != s){
s.close();
}
}
}
[/code]

這個是《深入淺出hibernate》中關於session管理的實現, 有些不明白。如果各位有比較好的對session管理的方法,大家都來說說。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章