Sunday, April 26, 2009

Read-Only transactions with Spring and Hibernate

Spring supports the concept of read-only transactions. Because Spring doesn't provide persistence functionality itself, the semantics of read-only transactions depend on the underlying persistence framework used along with Spring.

I use Spring with Hibernate and Oracle, and when I looked to understand the semantics of read-only transactions on this specific configuration, I found that there was very little information on the web. The existing information is scarce and not very clear, and as a result I had to do some research myself, which included hacking into Spring and Hibernate's source code. Not that I don't enjoy spending a few late hours reading good code, but so that you don't have to do it yourself, here is what I found.

Spring

Spring's documentation doesn't say almost anything about what a read-only transaction really means. The best information I could find was:

Read-only status: a read-only transaction does not modify any data. Read-only transactions can be a useful optimization in some cases (such as when using Hibernate).

That's basically all it says. Google and a little hacking shed some light on the real meaning of the sentence above: if the transaction is marked as read-only, Spring will set the Hibernate Session's flush mode to FLUSH_NEVER, and will set the JDBC transaction to read-only. Now lets understand what it means and what are the implications in a Hibernate/Oracle setup.

Hibernate

Hibernate doesn't have the concept of read-only sessions. But when a session's flush mode is set to FLUSH_NEVER, which is what Spring does, two interesting things happen. First, running HQL queries no longer cause Hibernate to flush the session state to the database, which can provide a dramatic performance improvement. Secondly, Hibernate will not flush the changes before commiting the transaction. But the user can still call Session.flush() by hand, causing any modifications to be persisted to database. This is where Spring's call to Connection.setReadOnly() comes handy.

Oracle

When using the Oracle JDBC driver, calling connection.setReadOnly(true) translates into the statement "SET TRANSACTION READ ONLY". This statement limits the types of SQL statements that can be executed during the transaction. Only SELECTS (without 'FOR UPDATE') and a few other statements can be executed. Specifically, no UPDATEs, DELETEs, INSERTs or MERGEs can be executed. This behavior is Oracle-specific. Other RDBMS can have different semantics for read only transactions or simply not support it at all.

By setting the JDBC connection to read-only, Spring prevents a distracted user from persisting changes by flushing the Hibernate session to the database.

Notes

As we saw, with the two measures taken by Spring, the transaction is guaranteed to be read-only through the JDBC connection, and performance improvements are obtained by setting the Hibernate session to FLUSH_NEVER.

There is one thing that doesn't happen, though. Even during Spring read-only transactions, Hibernate queries still save the state of persistent objects in the session cache. In theory it wouldn't be necessary, since this state is used to detect modifications during session flushes. Depeding on the size and number of objects it can make a huge difference in terms of memory usage.

If you still want to prevent Hibernate from saving the object state in the session cache, you have to manually run the HQL queries in read-only mode. It would be a nice improvement to Hibernate to have a read-only mode to the session so that no object state is stored and no flush executed.

15 comments:

Anonymous said...

Thanks! that was really useful.

Anonymous said...

I question the stmt in the last para:

If you still want to prevent Hibernate from saving the object state in the session cache, you have to manually run the HQL queries in read-only mode. It would be a nice improvement to Hibernate to have a read-only mode to the session so that no object state is stored and no flush executed.

The Hibernate Session has a method:

void setReadOnly(Object entity, boolean readOnly)

Set an unmodified persistent object to read only mode, or a read only object to modifiable mode.

This applies to the object, not to the entire session but it does what you want for the object.

Anonymous said...

thank you very much!! great helpfull post!!

Anonymous said...

You rock man. Great post. Keep it up.

Artem said...

"When using the Oracle JDBC driver, calling connection.setReadOnly(true) translates into the statement "SET TRANSACTION READ ONLY".
It's not true, oracle docs says that they do not support read-only connections (http://www.oracle.com/technology/docs/tech/java/sqlj_jdbc/doc_library/javadoc/oracle.jdbc.driver.oracleconnection.html#setReadOnly%28boolean%29). I also wrote simple test that confirms that. At least I could do SELECT ... FOR UPDATE w/o any exception.

Anonymous said...

Yup, helpful. Thanks.

Pepijn said...

Isn't the session cache also used to prevent having to load the same object twice? That's still useful, even for a read-only transaction.

Andrei said...

Artem is right. Unfortunately read-only connections are not supported by the Oracle JDBC Drivers.
Here's an excerpt from the JDBC Developer’s Guide and Reference
10g Release 2 (10.2):

"Read-only connections are supported by the Oracle server, but not by the Oracle JDBC drivers.

For transactions, the Oracle server supports only the TRANSACTION_READ_COMMITTED and TRANSACTION_SERIALIZABLE transaction isolation levels. The default is TRANSACTION_READ_COMMITTED."

So TRANSACTION_READ_ONLY isolation level cannot be set through the Oracle JDBC driver.

Ondrej Medek said...

Hi, AFAIK it is different when you set read only transaction and read-only JDBC connection on Oracle. But I have forgotten already the details.

Shrikant Patel said...

This really good article. I have question for author. You mention at the end that - "Even during Spring read-only transactions, Hibernate queries still save the state of persistent objects in the session cache".

What happens to these object that are change in cached?
Do they get written to database at any point?
If different session does flush, do these object get persisted at point of time?
If different session is trying to access object which is modified in cache by different read only session. will first session get the value from cache?

I would appreciate if you answer above.

Thanks in advance.

S├ębastien Lorber said...

Note that when using Spring with Hibernate you generally use HibernateTemplate...


And guess what? There's another security at this level:
org.springframework.orm.hibernate3.HibernateTemplate.checkWriteOperationAllowed(HibernateTemplate.java:1175)

Anonymous said...

I still don't understand 1 thing. Why should i use transaction annotation with readOnly mode when i don't want to change data?
What's the difference between method A with @transa(readOnly=true) and method B without such annotation?

Jose Beltran said...

Thank you so much.

Anonymous said...

"... The Hibernate Session has a method:

void setReadOnly(Object entity, boolean readOnly) ...
"

Actually Hibernate session has a plenty of useful methods, consider this one:

void setDefaultReadOnly(boolean readOnly)

Anonymous said...

Thank you so much for the info!