In my project I want to cache few objects but not whole table. So my problem is, is there a API that i could use to manually add objects to hibernate second level cache ? ( Or is there a way to specify table data region for second level cache ? )
Asked
Active
Viewed 1,657 times
3
-
I cannot think of any reason why would you want to do it. It is not your cache, so why would you mess up with it. The jpa will cache only the objects used (retrieved/saved to db...), so you can leave it to Hybernate to do its job (you can confiigure its size, behaviour though). If you need your own cache just uses Guava cache instead. – Zielu Feb 16 '15 at 12:15
1 Answers
4
You can annotate with @Cacheable(true) the entities you want to cache
@Cacheable(true)
@Entity
public class Person { ... }
and then in your persistence.xml configuration file, you need to set the shared-cache-mode
element to use ENABLE_SELECTIVE
:
<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
so now:
Caching is enabled for all entities for Cacheable(true) is specified. All other entities are not cached.
To specify regions, you can use the Hibernate specific @Cache
annotation:
@Cacheable(true)
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE, region="your-entity-region")
@Entity
public class Person { ... }
Now, you have to enable the 2nd-level cache:
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<property name="hibernate.cache.region.factory_class">ehcache</property>
To add entities to the 2nd level cache, you just need to just load the entity (and it will be cached automatically):
Person person = entityManager.find(Person.class, 1L);

Vlad Mihalcea
- 142,745
- 71
- 566
- 911
-
1This is helpful. But i want to cache only SOME of `Person` objects. The reason is there are two many persons and caching all those might be a issue ( with memory and at application start all the objects are cached ). Therefore I want only Persons with certain condition ( ex : age > 50 ) to be in cache and these should be loaded at application start-up. – Viraj Feb 16 '15 at 12:33
-
2if you run that query, only the entities you select are going to be cached and not the whole entities in the DB. That's how the 2nd level cache works. – Vlad Mihalcea Feb 16 '15 at 12:44
-
1Yes. But eventually large set of data will be in cache ( when data get read) . Is there a way to control objects which should cache using above condition permanently. ( age <= 50 won't be cache under any condition ). Problem is I cannot change the class structure to support this. – Viraj Feb 16 '15 at 12:49
-
1You can call `entityManager.evict(entity)` for all the entities you don;t want to be stored in the cache. – Vlad Mihalcea Feb 16 '15 at 12:56