Search code examples
sqlhibernatespringrollback

Hibernate Template with Transactions


I have a java/spring webapp which uses HibernateTemplate and I was wondering if it was possible to use SQL transactions with hibernate template.

For example, suppose that I have the following dao code:

getHibernateTemplate().save(newObject);
getHibernateTemplate().saveOrUpdate(someObject);
getHibernateTemplate().delete(oldObject);

Suppose that I want either all three statements to succeed or all three to fail. Is there any way to accomplish this with hibernate template? Can I use a try/catch block? If so, what would I put in the catch block to rollback the hibernate template statements?


Solution

  • Use Spring to manage your transactions (I see it as one of your tags).

    The basic idea is that you group a bunch of persistence operations, that you want to all participate in one transaction, in one method (in a service class), and you configure Spring to make that service method transactional.

    One relatively easy way to do it is to configure spring to make all service methods transactional, but you are not constrained to this -- you can make it as easy or complicated as you want.