-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 
Author Message
 Post subject: Hello!every one!I come from China,here`s a question
PostPosted: Tue Jul 25, 2006 4:13 am 
Newbie

Joined: Tue Jul 25, 2006 3:57 am
Posts: 1
Now,I want to put the Session into the ThreadLocal(),so the Session can be shared in the lcoal thread,and in one Thread we just need one Session,but there are some Exceptions where it runs for sometimes.

here are my codes,my English is poor so forgive me,thanks all

package dao.imp.hibernate;
import ..........

public abstract class _RootDAO {
private static SessionFactory sessionFactory;
//-----------make a ThreadLocal to hold new Session----------------
private static final ThreadLocal sessionLocal = new ThreadLocal();
public static void initialize() throws HibernateException {
if (sessionFactory == null) {
Configuration cfg = new Configuration();
cfg.configure();
sessionFactory = cfg.buildSessionFactory();
}
}

protected SessionFactory getSessionFactory() throws HibernateException {
if (null == sessionFactory)
throw new RuntimeException(
"You must call initialize()) in _RootDAO");
else
return sessionFactory;
}
//建立Session,当Thread共享Session已经存在的时候,直接返回Session,不存在则新建Session,并记录在ThreadLocal中

protected Session getSession() throws HibernateException {
Session s = (Session)sessionLocal.get();
if(s == null){
s = getSessionFactory().openSession();
sessionLocal.set(s);
return (Session)sessionLocal.get();
}else{
return s;
}
}

//----------and here are some DB options----------------
public java.util.List find(String query) throws HibernateException {
Session s = null;
try {
s = getSession();
return find(query, s);
} finally {
//if (null != s)
//s.close();
}
}
..............

//----------DB options end

//--------when the object is killed,I want to mack sure that the session
//--------is closed.
public void finalize()throws Throwable{
Session s = (Session)sessionLocal.get();
if(s!=null){
try{
s.close();
}catch(Exception e){
e.printStackTrace();
}
}
}

}


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.