Reputation: 401
How to configure hibernate for rolling back transactions in the associated tables in case of exceptions? I have a Transaction table and there are associated tables in which data needs to be persisted to but if something goes wrong i want to rollback all of them.
Upvotes: 0
Views: 299
Reputation: 2439
A transaction is a database feature that guarantees atomicity. It's always started and committed or rolled back on the database level.
Using the Hibernate you can start, commit or rollback the transaction. (Suppose you have an instance of Hibernate SessionFactory
)
Session session = sessionFactory.getCurrentSession();
session.getTransaction().begin();
try {
// perform some data changes ...
session.getTransaction().commit(); // will save all changes
} catch (Exception e) {
session.getTransaction().rollback(); // will discard all changes
throw e;
} finally {
session.close();
}
After you start a transaction you can start changing data in different tables. All changes that have been done in the scope of transaction will be either committed or rolled back.
Please note, that when you use Hibernate to start the transaction, it calls JDBC Driver under the hood (see JDBC transactions), and the driver uses a proper SQL query to start a transaction (see PostgreSQL START TRANSACTION).
You should not manage transactions manually in real projects. Frameworks like Spring provide much more sophisticated declarative transaction management.
Upvotes: 1