Hi,
I have couple of Questions using ThreadLocal in J2EE server deployment.
1. Whats the recommended way of managing hibernate session, I mean, is it OK to use ThreadLocal to get the session object.
2. I am currently using ThreadLocal to get my Session and having the following error.
Code giving the session
public static Session currentSession() throws DaoException {
Session s = (Session) threadLocal.get();
try {
if(s == null) {
if (sf == null) {
try {
loadClasses();
sf = cfg.buildSessionFactory();
}
catch(Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
s = sf.openSession();
threadLocal.set(s);
}
}
catch (HibernateException he) {
throw new DaoException(he);
}
return s;
}
my DAO has methods like this:
public Location getLocationByPk(String locId) throws DaoException {
Location loc = null;
Session sess = getSession();
try {
loc = (Location) sess.get(Location.class, locId);
return loc;
} catch (HibernateException e) {
throw new DaoException("Error Creating Query: getLocationByPk() " + e.getMessage());
} finally {
closeSession(sess);
}
}
public State getStateByPk(String stateId) throws DaoException {
Session sess = getSession();
State loc = null;
try {
loc = (State) sess.get(State.class, stateId);
return loc;
} catch (HibernateException e) {
throw new DaoException("Error Creating Query: getStateByPK() " + e.getMessage());
} finally {
closeSession(sess);
}
}
public static void main(String[] args) {
try {
Location temp = dao.getLocationByPk("HQ");
State st = dao.getStateByPk("NV");
temp.setStateId("NV");
dao.updateLocation(temp);
} catch (DaoException e) {
e.printStackTrace();
}
}
Giving the error after executing the first getLocationByPK();
net.sf.hibernate.HibernateException: Session is closed
at net.sf.hibernate.impl.SessionImpl.connection(SessionImpl.java:3250)
at net.sf.hibernate.impl.BatcherImpl.prepareQueryStatement(BatcherImpl.java:65)
at net.sf.hibernate.loader.Loader.prepareQueryStatement(Loader.java:704)
at net.sf.hibernate.loader.Loader.doQuery(Loader.java:185)
at net.sf.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:133)
at net.sf.hibernate.loader.Loader.loadEntity(Loader.java:831)
at net.sf.hibernate.loader.Loader.loadEntity(Loader.java:851)
at net.sf.hibernate.loader.EntityLoader.load(EntityLoader.java:57)
at net.sf.hibernate.loader.EntityLoader.load(EntityLoader.java:49)
at net.sf.hibernate.persister.EntityPersister.load(EntityPersister.java:419)
at net.sf.hibernate.impl.SessionImpl.doLoad(SessionImpl.java:2081)
at net.sf.hibernate.impl.SessionImpl.doLoadByClass(SessionImpl.java:1955)
at net.sf.hibernate.impl.SessionImpl.get(SessionImpl.java:1891)
My question is:
1.Do I need to close the session at all in the methods..?
2. Is it a problem thats arising because of ThreadLocal..?
Thanks
|