3

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?

1
  • can you add code you use for the query? do your objects have entity keys? Commented Apr 7, 2013 at 23:35

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm not quite follow what the Entity Key means here? is the @Id property of the Entity?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.