1

From the following source : hibernate transaction eg.

It is written that, A typical transaction should use the following idiom:

Session sess = factory.openSession();
 Transaction tx;
 try {
     tx = sess.beginTransaction();
     //do some work
     ...
     tx.commit();
 }
 catch (Exception e) {
     if (tx!=null) tx.rollback();
     throw e;
 }
 finally {
     sess.close();
 }

My question is what does tx object have if it goes in catch block i.e. any exception occurs and is this the result of tx.commit()?? And if yes, then how, because it returns nothing. I mean to ask that when and where the value of tx is changing and to what?

Quesion 2) Is it necessary to begin transacion in case of read only transactions i.e. select queries ..

Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
sagar
  • 725
  • 2
  • 13
  • 30
  • You need a transaction for a select if you have some lazy collections or proxy entities in your entity and you want to use them (for example by calling entity.getMyLazyList()). And I didn't get your first question – Multisync Oct 18 '14 at 20:47

1 Answers1

2
  1. If the exception occurs in:

    tx = sess.beginTransaction();

    Then tx will be null so nothing will happen.

    If the exception is thrown after tx was assigned, then tx represents a database transaction hook. You should always rollback transactions on exceptions because some database drivers might not do it automatically.

  2. Yes, you should use transactions for read-only queries too.

Community
  • 1
  • 1
Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911