Skip to content
Advertisement

Why do I need Transaction in Hibernate for read-only operations?

Why do I need Transaction in Hibernate for read-only operations?

Does the following transaction put a lock in the DB?

Example code to fetch from DB:

Transaction tx = HibernateUtil.getCurrentSession().beginTransaction(); // why begin transaction?
//readonly operation here

tx.commit() // why tx.commit? I don't want to write anything

Can I use session.close() instead of tx.commit()?

Advertisement

Answer

Transactions for reading might look indeed strange and often people don’t mark methods for transactions in this case. But JDBC will create transaction anyway, it’s just it will be working in autocommit=true if different option wasn’t set explicitly. But there are practical reasons to mark transactions read-only:

Impact on databases

  1. Read-only flag may let DBMS optimize such transactions or those running in parallel.
  2. Having a transaction that spans multiple SELECT statements guarantees proper Isolation for levels starting from Repeatable Read or Snapshot (e.g. see PostgreSQL’s Repeatable Read). Otherwise 2 SELECT statements could see inconsistent picture if another transaction commits in parallel. This isn’t relevant when using Read Committed.

Impact on ORM

  1. ORM may cause unpredictable results if you don’t begin/finish transactions explicitly. E.g. Hibernate will open transaction before the 1st statement, but it won’t finish it. So connection will be returned to the Connection Pool with an unfinished transaction. What happens then? JDBC keeps silence, thus this is implementation specific: MySQL, PostgreSQL drivers roll back such transaction, Oracle commits it. Note that this can also be configured on Connection Pool level, e.g. C3P0 gives you such an option, rollback by default.
  2. Spring sets the FlushMode=MANUAL in case of read-only transactions, which leads to other optimizations like no need for dirty checks. This could lead to huge performance gain depending on how many objects you loaded.

Impact on architecture & clean code

There is no guarantee that your method doesn’t write into the database. If you mark method as @Transactional(readonly=true), you’ll dictate whether it’s actually possible to write into DB in scope of this transaction. If your architecture is cumbersome and some team members may choose to put modification query where it’s not expected, this flag will point you to the problematic place.

Advertisement