Hibernate HQL only hits session cache
Asked Answered
G

1

7

I am having some trouble understanding where an HQL query gets the information from. My project is using different threads and each thread reads/writes to the database. Threads do not share Session objects, instead I am using a HibernateUtil class which creates sessions for me.

Until recently, I would only close a session after writing but not after reading. Changes to objects would be immediately seen in the database but when reading on other threads (different Session object than the one used for writing) I would get stale information. Reading and writing happened always on different threads which means different Session objects and different session caches.

I always thought that by using HQL instead of Criteria, I would always target the database (or second level cache) and not the session cache but while debugging my code, it was made clear to me that the HQL was looking for the object in the session cache and retrieved an old outdated object.

Was I wrong in assuming that HQL always targets the database? Or at least the second level cache?

PS: I am using only one SessionFactory object.

Golter answered 10/5, 2012 at 11:27 Comment(0)
C
8

Hibernate has different concepts of caching - entity caches, and query caches. Entity caching is what the session cache (and the 2nd level cache, if enabled) does.

Assuming query caching is not enabled (which it's not, by default), then your HQL would have been executed against the database. This would have returned the IDs of the entities that match the query. If those entities were already in the session cache, then Hibernate would have returned those, rather than rebuilding them from the database. If your session has stale copies of them (because another session has updated the database), then that's the problem you have.

I would advise against using long-lived sessions, mainly for that reason. You should limit the lifespan of the session to the specific unit of work that you're trying to do, and then close it. There's little or no performance penalty to doing this (assuming you use a database connection pool). Alternatively, to make sure you don't get stale entities, you can call Session.clear(), but you may end up with unexpected performance side-effects.

Clercq answered 10/5, 2012 at 11:34 Comment(2)
so the first time my session object performs the HQL query it targets the db. the result is then stored in the session cache. then the second time i perform the same HQL query, it reads the cache instead of targeting the database. this is the default behavior. have i understood this correctly? ps: indeed, closing sessions after each read and write (short lived Session objects) solves my problem.Golter
@alegen: The HQL will be run against the database each time, but the Java objects that are the end result of that query may come from the session cache. This is the default behaviour.Clercq

© 2022 - 2024 — McMap. All rights reserved.