Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate Second level Cache <<net.sf.ehcache.hibernate.EhCacheProvider>>

I want use second level cache in my hibernate Project but I just know a little about hibernate second level cache, can any one explain how shoud I use this in my code and what configuration and .jar file I need? I set these setting to my hibernate.cfg.xml file

 <property name="hibernate.cache.use_query_cache">true</property>
    <property name="hibernate.cache.use_second_level_cache">true</property>
    <property name="hibernate.cache.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</property>

and add these jar file ehcache-1.6.1.jar, ehcache-1.6.1-javadoc.jar, ehcache-1.6.1-sources.jar I want know shoud I change any other configuration?

and how can I understand that my project uses Second level cache?

if just put this setting, hibernate automatically use this or I must use ant other code in my .java class(like any annotation or something else)

like image 639
Am1rr3zA Avatar asked Jan 24 '23 09:01

Am1rr3zA


2 Answers

The annotation you're looking for is org.hibernate.annotations.Cache. Basic usage is:

@Entity
@Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public MyEntity {
    ...

  @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
  public List<ElementType> getSomeCollection() {
    ...
  }
}

For queries, you need to enable query cache by setting hibernate.cache.use_query_cache property to true AND specify that query is cacheable in its declaration (for named queries) or by calling setCacheable(true) on query instance.

All that said, you need to be really careful with caching and REALLY UNDERSTAND what you're doing, otherwise it'll do more harm than help. Don't look at it as "quick fix" - caching everything, for example, is definitely the wrong thing to do.

like image 162
ChssPly76 Avatar answered Jan 25 '23 22:01

ChssPly76


Your settings will make the second-level and query caches available for use in your project, but you still need to enable it for specific entities, collections, and queries. This requires some careful planning because there are trade-offs that you'll need to understand. In general, the second-level and query caches are appropriate for read-only or read-mostly data, but not volatile data. If you don't already own it, I would recommend picking up a copy of Java Persistence with Hibernate. It has a very good treatment of the subject.

like image 29
Rob H Avatar answered Jan 25 '23 22:01

Rob H