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();
}
}
}
}
|