views:

25

answers:

1

Probably it is a basic question, but could not found the answer anywhere in the web.

I am trying to use a second level cache (using ehcache) and just checked that some objects were being retrieved from database every time I tried to load them, the only difference was that I was not getting them by id but by a property that carries a SEO friendly name that are used to create urls on the system I am working. Is jpa/hibernate able to retrieve objects from cache just by with the id of the obj? Is there any way to get it working without need to activate the query cache?

+1  A: 

Is jpa/hibernate able to retrieve objects from cache just by with the id of the obj?

Yes, the second level cache works for query that looks for a single object based on Id i.e. when using EntityManager.find() or EntityManager.getReference() (or the equivalent Session#get() and Session#load() from the Hibernate API). AFAIK, this applies to all JPA implementations.

Is there any way to get it working without need to activate the query cache?

With standard JPA, I don't see any other option than using the Query Cache.

But if you don't mind using Hibernate API, there might be an alternative with Query#iterate(). With Query#iterate(), Hibernate will issue a SQL query that will fetch only the IDs and when you iterate over the results, it will load the corresponding entities from the cache.

Obviously, Query#iterate() will be much slower than Query#list() if you're not using a second level cache.

Personally, I'd use the query cache.

See also

Pascal Thivent
Many thanks ...
@user430830: You're welcome.
Pascal Thivent