I'm using hibernate to run a named JPA query.
The query is executed twice from the same session, the query should return same rows because database doesn't change in the mean time.
To my surprise, the objects returned from the query are different from these two query result lists (data is same but objects are different). With the first-level cache enabled (by default), I thought the second query should return the same objects as the first query?
The query is a simple named-query:
SELECT e from TABLE e where e.name=?1
Is cache bypassed by the query somehow? Or my understanding of the first-level cache is wrong?
These results greatly depend on whether you provide an Entity Id for your objects or not.
Also Session cache and Query caches are two different things in Hibernate.
If you load object with the same Entity Id from the same session it will return the same object.
But if you use query to load the object - it's a different story. Using query cache is supposed to return the same data no matter what Entity Ids you have.
Query cache is not turned on by default. You'll have to do something like query.setCacheable(true); to ensure that query is cached. Or set the hibernate.cache.use_query_cache property in Hibernate config file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With