This blog is mainly about Java...

Saturday, September 27, 2008

How to enable second level caching in Hibernate

To enable second level caching in hibernate you can do it two ways:
One of them is by creating a namedQuery and put it as cacheable and then call the namedQuery.

In your Entity class type
@NamedQueries( { @NamedQuery(name = "findAllDistinctPersons", query = "SELECT DISTINCT p FROM Person p", hints = {
@QueryHint(name = "org.hibernate.cacheable", value = "true"), @QueryHint(name = "org.hibernate.cacheRegion", value = "alkohol_register") }) })

Here I have created a NamedQuery called findAllDistinctPerons, and I put hints to be org.hibernate.cacheable as value true. Then you can if you want put a region.
This is optional. This basically means that you can define a region in your configuration file and define which part of the application should use this region.
You should do this if you want some region to be cacheable and some region not to be, but still want to reuse the object.

The other way is doing it when you are creating the query.
personList = entityManager.createQuery("SELECT DISTINCT p FROM " + Person.class.getName() + " p INNER JOIN p.personAdresseAdressetypes paa " +
"WHERE p.aktiv = " + getSearchAktiv() + " "
+ SearchHelper.getAdresseSearch(getSearchStringAdresse(),true, "paa")).setHint("org.hibernate.cacheable", true).getResultList();
Here you set the Hint directly on the query. Note that we are not defining any region here.

No comments:

Labels