hi, newbie here. trying to write some dao's for some db's. i found the code on the hiberate site that wraps a session in a thread local. but it seems to me that you may want to wrap a transaction also to eliminate a lot of code duplication that would occur. so i came up with the following code (see below).
as you can see, i really have no clue as to what should be done when certain exceptions are thrown.
has anyone had any success with something like this?
the main purpose is to allow the callers to dao's or methods in dao's to decide what constitutes a transaction. this would seem to be different between say wriing test cases for a db, or writing a piece if business logic in the domain layer, or writing code in a web app.
any comments would be appreciated.
thanks
Code:
package hib;
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*;
//thread safe session and transaction wrapper
public class CSAT {
public CSAT(final SessionFactory sessionFactory) {
this.sessionFactory= sessionFactory;
}
public Session currentSession() throws HibernateException {
SAndT st= (SAndT)sAndT.get();
if (st.s == null) {
st.s= sessionFactory.openSession();
st.wasClosed= false;
}
return st.s;
}
public void closeSession() throws HibernateException {
SAndT st= (SAndT)sAndT.get();
if (st.s != null)
try {
if (st.tx != null) {
st.tx.rollback();
st.wasRolledBack= st.tx.wasRolledBack();
st.wasCommitted= !st.wasRolledBack;
}
st.s.close();
st.wasClosed= true;
} catch (HibernateException e) {
throw e;
} finally {
st.tx= null;
st.s= null;
}
}
public Transaction currentTransaction() throws HibernateException {
SAndT st= (SAndT)sAndT.get();
if (st.s == null)
st.s= sessionFactory.openSession();
if (st.tx == null) {
st.tx= st.s.beginTransaction();
st.wasCommitted= st.wasRolledBack= false;
}
return st.tx;
}
public void commitTransaction() throws HibernateException {
SAndT st= (SAndT)sAndT.get();
if (st.tx != null)
try {
st.tx.commit();
st.wasCommitted= st.tx.wasCommitted();
st.wasRolledBack= !st.wasCommitted;
} catch (HibernateException e) {
st.tx.rollback();
st.wasRolledBack= st.tx.wasRolledBack();
st.wasCommitted= !st.wasRolledBack;
throw e;
} finally {
st.tx= null;
}
}
static CSAT fromConfiguration(final Configuration configuration) {
try {
SessionFactory sf= configuration.buildSessionFactory();
return new CSAT(sf);
} catch (HibernateException e) {
throw new RuntimeException("Configuration problem: " + e.getMessage());
}
}
private final SessionFactory sessionFactory;
private final ThreadLocal sAndT= new ThreadLocal();
{
sAndT.set(new SAndT());
}
public static CSAT po_db4; // hack, move this later, not thread safe at all!
}
class SAndT { // holder for sesssion and transaction
Session s;
Transaction tx;
boolean wasClosed, wasCommitted, wasRolledBack;
}