Sunday, 21 April 2019

Difference between a First-level and a Second-level Cache in Hibernate

Caching guarantees that each entity is loaded once in a persistence context; so that it reduces database accesses due to repeated data visiting.

For the Hibernate:

A first-level cache is a session scoped cache. it is used in the current session alone(isolated from another session). When the current session is closed, the cached entities go to end. The first-level is achieved by default, the developer doesn't need to do anything. When you first time to query an entity it will be loaded in the first-level cache; afterwards, the queries on this entity will be on the cached instance.

removing an object from the first-level cache, evict()
removing all object from the first-level cache, clear()

A second-level cache is a session-factory scoped cache. it means that it is shared by all sessions. The developer needs to set up the second-level cache. Hibernate only provides a second-level cache interface; it works as a bridge connecting hibernate with the cache provider.

1) config. the persistence XML
enable the 2nd level cache

2) modify the entity
decorating with @cachable: make an entity eligible for 2nd level cache.
decorating with @cache: picking up a cache concurrency strategy.

  • read_only: used for entities that never change
  • nonstrict_read_write: 
  • read_write: 
  • transactional: 




3) collection by default is not cached.


https://www.baeldung.com/hibernate-second-level-cache

No comments:

Can Jackson Deserialize Java Time ZonedDateTime

Yes, but must include JSR310. Thus ZonedDateTime can be deserialized directly from JSON response to POJO field. <dependency> <g...