Saturday, 22 January 2011

Second Level Caching

JPA has two levels of caching. The first level of caching is the persistence context (which can be either transaction scoped or extended.), and the second level of caching, introduced in JPA 2.0, sites in between the entity manager and the database.

With second level caching entities not found in the persistence context will be loaded from the second level cache, and if not found there, from the database. The ideal type of entity to live in the second level cache are those that are rarely updated, or those that are constantly read.

To mark an entity as requiring caching, you can use the @Cacheable annotation as below:

@Entity
@Cacheable(true)
public class Person {

    @Id @GeneratedValue
    private Long id;
    private String name;

    // etc ...
}

To override the provider-specific defaults for managing cached entities, you can set the shared-cache-mode value in the persistence.xml. The possible values are below:
  • ALL- all entities are cached
  • DISABLE_SELECTIVE - all entities cached apart from those with the annotation @Cacheable(false)
  • ENABLE_SELECTIVE - only entities with the annotation @Cacheable(true) are cached
  • NONE - no caching for the persistence unit
  • UNSPECIFIED - provider-specific default
JPA 2.0 also introdcued the Cache interface which can be used to evict or invalidate entities in the second level cache. It can claso be used to check whether ot not an entity exisits in the cache as well.

Finally, you cannot implement a caching strategy without also considering a locking strategy (but that's for another post!)

No comments:

Post a Comment

Note: only a member of this blog may post a comment.