关于Hibernate 中使用 ThreadLocal 管理 Session 的疑惑.
这是网上使用的一段代码,但我感觉有几个问题.
如果同时调用两次 currentSession() 得到的是同一个 Session,一旦关闭一个,另一个也就关闭了。
在这样的情况下,如果做包含查询,子查询一但关闭了Session就会出错. 我希望每个Session有自己的
ThreadLocal,应该如何做,比较好.
public static final ThreadLocal session = new ThreadLocal();
public static Session currentSession() throws 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 (s != null)
s.close();
}
}
问题点数:200、回复次数:4Top
1 楼catblue(佛家说:一粒沙中看世界。)回复于 2004-12-04 15:25:54 得分 60
不会,帮你顶一下。Top
2 楼zh_baiyu(SkyBay)回复于 2004-12-04 16:12:56 得分 60
顶,干点力气活Top
3 楼cm4ever(小P[Fly Away])回复于 2004-12-05 00:40:50 得分 80
//注意:这里的session用完之后并不close,而只flush一下
public void delCat(String strCatId) {
try {
Session s = HibernateSessionFactory.currentSession();
Object cat = s.load(Cat.class, strCatId);
s.delete(cat);
s.flush();
} catch (HibernateException e) {
e.printStackTrace();
}
}
----------
http://www.hibernate.org.cn:8000/92.htmlTop
4 楼CAYU(中原)回复于 2004-12-05 19:27:12 得分 0
网上的代码被简化了,很不安全,spring 的方法
Steve Ebersole: Here is a variation on the above ThreadLocalSession. The main difference is that it undersands the concept of nested calls. Note that this usage is meant specifically for use in CMT session beans.
public class ThreadLocalSession
{
private static final ThreadLocal sessionContext = new ThreadLocal();
private Session session;
private int level;
public static Session currentSession()
throws HibernateException
{
SessionFactory factory = ...;
ThreadLocalSession tlSession = (ThreadLocalSession)sessionContext.get();
if (tlSession == null)
{
tlSession = new ThreadLocalSession();
tlSession.session = factory.openSession();
tlSession.level = 0;
sessionContext.set( tlSession );
}
tlSession.level++;
return tlSession.session;
}
public static void closeSession()
throws HibernateException
{
ThreadLocalSession tlSession = (ThreadLocalSession)sessionContext.get();
if (tlSession == null)
{
return;
}
tlSession.level--;
if (tlSession.level <= 0)
{
if (tlSession.session != null && tlSession.session.isOpen())
{
tlSession.session.close();
}
sessionContext.set( null );
}
}
}
Top




