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()
?
You might actually have reasons to mark transactions as read-only.
autocommit=true
if different option wasn't set explicitly.@Transactional(readonly=true)
, Spring will set the JDBC transaction into a read-only mode, thus 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 would point you to the problematic place.To sum up - you can go both ways, but you need to understand consequences.