Hibernate version:
2.1.7
Hello there! I always thought that I was doing the things right using transactions. My HibernateDAO has this pattern:
Code:
public void update(Entity obj) throws PersistenceException {
Session session = getCurrentSession();
beginTransaction();
try {
session.update(obj);
} catch (HibernateException e) {
logger.error(e);
rollbackTransaction();
throw new PersistenceException(e);
} finally {
commitTransaction();
closeSession();
}
}
public static Session getCurrentSession(){
Session s = (Session)threadSession.get();
if(s == null){
try{
s = sessionFactory.openSession();
threadSession.set(s);
}catch(HibernateException e){
e.printStackTrace();
throw new RuntimeException(e);
}
}
return s;
}
public static void closeSession(){
Session s = (Session)threadSession.get();
threadSession.set(null);
if(s!= null && s.isOpen()){
try {
s.close();
} catch (HibernateException e) {
throw new RuntimeException(e);
}
}
}
public static void beginTransaction() {
Transaction tx = (Transaction) threadTransaction.get();
try {
if (tx == null) {
tx = getCurrentSession().beginTransaction();
threadTransaction.set(tx);
}
} catch (HibernateException ex) {
}
}
public static void commitTransaction() {
Transaction tx = (Transaction) threadTransaction.get();
try {
if ( tx != null && !tx.wasCommitted()
&& !tx.wasRolledBack() )
tx.commit();
threadTransaction.set(null);
} catch (HibernateException ex) {
rollbackTransaction();
throw new RuntimeException(ex);
}
}
public static void rollbackTransaction() {
Transaction tx = (Transaction) threadTransaction.get();
try {
threadTransaction.set(null);
if ( tx != null && !tx.wasCommitted()
&& !tx.wasRolledBack() ) {
tx.rollback();
}
} catch (HibernateException ex) {
throw new RuntimeException(ex);
} finally {
closeSession();
}
}
All methods looks like these. Well I was happy. was...
Untill I deal with this:
(while it.hasNext()){
Pojo pojo = (Pojo)it.next();
//do some fancy code here
dao.update(pojo);
}
So, at a given point, an error happens. Well, with this type of code, all the previous iterations changed the database. Something totally undesirable. Even setRollBackOnly() (I'm using SLSBs) can't do anything (pretty obvious, since I've commited every unit)
Anyway, which is the right way to perform a single block of transaction? To be a real ACID application?
Best regards
Vinicius