Perform any DB operation in an isolated transaction

28 / Jul / 2015 by Anil Agarwal 1 comments

Hi Friends,

Sometimes we need to perform any DB operation in between a transaction, but due to transaction’s property, it’s getting committed only once the parent transaction will be finished.

If you need to perform any operation that need to be committed immediately, irrespective of parent transaction (Example : for a dependent queuing operation etc.) like a isolated transactional operation, we can do so like this

org.hibernate.Session session = HibernateUtil.sessionFactory.openSession();
Transaction tx = null;
try {
   tx = session.beginTransaction();
   //Perform any DB operation in an Isolated Transaction here
   object.save(flush: true);
   tx.commit();
}catch (Exception e) {
   if (tx != null) tx.rollback();
   e.printStackTrace();
}finally {
   session.close();
}

If using grails we can do the same like this

DomainName.withTransaction { Transaction tx ->
 //Perform any DB operation in an Isolated Transaction here
   object.save(flush: true);
   tx.commit();
}

Cheers !!!

 

FOUND THIS USEFUL? SHARE IT

comments (1 “Perform any DB operation in an isolated transaction”)

Leave a comment -