Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Transactions in Hibernate

Tags:

java

hibernate

Is there any risk to call beginTransaction on one session multiple times? I mean for example:

session.beginTransaction();
session.saveOrUpdate(object1);
// .... some works
session.beginTransaction();
session.delete(object2);
// ... some other works
session.getTransaction.commit();


I did this and it seems there is no problem (any exception or warning). In fact I want to know what happens when I use transaction in such a way.

like image 542
Hamzeh Avatar asked Feb 23 '23 08:02

Hamzeh


2 Answers

The javadocs give an explanation

beginTransaction() Begin a unit of work and return the associated Transaction object. If a new underlying transaction is required, begin the transaction. Otherwise continue the new work in the context of the existing underlying transaction. The class of the returned Transaction object is determined by the property hibernate.transaction_factory.

So - it has no effect, it continues using the existing transaction. So don't do it, as it might confuse readers (including you). You can have multiple transactions if you commit the first and then start the second.

like image 153
Bozho Avatar answered Feb 25 '23 22:02

Bozho


Yes. There wont be any compile/run time exceptions thrown. However there are undesired results that might come up, resulting in the partly unsaved data. I have faced this issues sometime back.

like image 20
Sathwick Avatar answered Feb 25 '23 22:02

Sathwick