ChatGPT解决这个技术问题 Extra ChatGPT

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()?

Transaction is required by the DB itself. You can read about autocommit mode here: community.jboss.org/wiki/…
@BheshGurung i guess we require transcation only for write operation
Did you read "Debunking auto-commit myths" part in the link?

S
Stanislav Bashkyrtsev

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

Read-only flag may let DBMS optimize such transactions or those running in parallel. 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

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. 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.


Thanks for replying.I am using hibernate (native hibernate ,not jpa).But hibernate forces me to start a transcation before doing any db operation.If i dont start one it throws error saying no active tracscationn.Can i mark transcation as read only , if yes how?
The readonly flag is actually set for connection, not for transaction itself, and you can't access it via Hibernate just like that. You need to use Spring Transaction support and use either annotations or XML based transactional configuration. By doing that Spring takes the ownership of connection and transaction management instead of Hibernate.
Very well explained ! Another article from Mark Richards explains pretty well the pitfalls of read-only flag in Transactional annotation - ibm.com/developerworks/java/library/j-ts1/index.html.
V
Vlad Mihalcea

All database statements are executed within the context of a physical transaction, even when we don’t explicitly declare transaction boundaries (e.g., BEGIN, COMMIT, ROLLBACK).

If you don't declare transaction boundaries explicitly, then each statement will have to be executed in a separate transaction (autocommit mode). This may even lead to opening and closing one connection per statement unless your environment can deal with connection-per-thread binding.

Declaring a service as @Transactional will give you one connection for the whole transaction duration, and all statements will use that single isolation connection. This is way better than not using explicit transactions in the first place.

On large applications, you may have many concurrent requests, and reducing database connection acquisition request rate will definitely improve your overall application performance.

JPA doesn't enforce transactions on read operations. Only writes end up throwing a TransactionRequiredException in case you forget to start a transactional context. Nevertheless, it's always better to declare transaction boundaries even for read-only transactions (in Spring @Transactional allows you to mark read-only transactions, which has a great performance benefit).


"... then each statement will have to be executed in a separate transaction". The container doesn't do Batch Processing automatically?
Thanks Vlad. I read some of your articles. They are really useful.
This stackoverflow.com/q/34797480/179850 seems to contradict a bit your affirmation that read only transactions have great performance benefit. At least, it doesn't seem to be the case in the context of hibernate.
No, it doesn't. That's about setting read-only, while mine is about avoiding auto-commit.
H
Hearen

Transactions indeed put locks on the database — good database engines handle concurrent locks in a sensible way — and are useful with read-only use to ensure that no other transaction adds data that makes your view inconsistent. You always want a transaction (though sometimes it is reasonable to tune the isolation level, it's best not to do that to start out with); if you never write to the DB during your transaction, both committing and rolling back the transaction work out to be the same (and very cheap).

Now, if you're lucky and your queries against the DB are such that the ORM always maps them to single SQL queries, you can get away without explicit transactions, relying on the DB's built-in autocommit behavior, but ORMs are relatively complex systems so it isn't at all safe to rely on such behavior unless you go to a lot more work checking what the implementation actually does. Writing the explicit transaction boundaries in is far easier to get right (especially if you can do it with AOP or some similar ORM-driven technique; from Java 7 onwards try-with-resources could be used too I suppose).


I
Ingo

It doesn't matter whether you only read or not - the database must still keep track of your resultset, because other database clients may want to write data that would change your resultset.

I have seen faulty programs to kill huge database systems, because they just read data, but never commit, forcing the transaction log to grow, because the DB can't release the transaction data before a COMMIT or ROLLBACK, even if the client did nothing for hours.