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 ? )
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.