We are using Hibernate with JPA in a project we are currently developing. Currently running on Wildfly and future possiblity is the commercial version depending on needs.
Some alternatives for the 2nd level cache are listed in the Hibernate documentation here. There also exist other solutions such as Hazelcast. Among alternatives it seems JBoss is officially supporting an Infinispan solution.
As the case in many projects, we have some tables that will rarely change if ever at all, such as a list of cities, the statuses a project can have etc. Hence our decision to use the 2nd level cache for such cases.
Hibernate second level cache uses a common cache for all the session object of a session factory. It is useful if you have multiple session objects from a session factory. SessionFactory holds the second level cache data. It is global for all the session objects and not enabled by default.
Why Is a Second-Level Cache Important for Hibernate? A second-level cache improves application performance with regard to persistence for all sessions created with the same session factory.
By default, all query cache results are stored in the org. hibernate. cache.
SessionFactory object holds the second level cache data. The data stored in the second level cache will be available to entire application. But we need to enable it explicitly.
The second-level cache is a relation-data cache and not a full-blown object caching solution. So it's just the basic entity properties and the foreign keys that get saved. As for entity associations, the *-To-One might be saved in different cache regions while the *-To-Many relationships require enabling the query cache too.
I think the 2nd level cache is much more useful when your entities actually change from time to time. The 2nd level cache entry is invalidated when an entity is being determined as dirty.
But if you rarely change your data, it's probably better to use an actual object cache. The object cache will store the whole object relationship tree and it's a much better alternative if you mainly operate on entities, as opposed to free-style joining projections.
So if your workflows revolve around entities with hierarchies then an object cache is more appropriate.
If your application doesn't actually operate with entities but with various data joining projections then you should add DB indexes and make sure there's enough RAM for the DB server to serve data from memory, without hitting the disk.
Solution:
I recommend you using HazelCast, which is a high-performance in-memory data grid. HazelCast allows you to either integrate it as a 2nd level cache or you can save whole object graphs if you want it. Just follow their documentation on how you can integrate it into your current application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With