Search code examples
javahibernateormsecond-level-cachequery-cache

understanding hibernate cache


If I have this method in object class:

@OneToMany( fetch = FetchType.EAGER,
    cascade = { CascadeType.ALL },
    mappedBy = "object"  )
@org.hibernate.annotations.Cascade(
    {org.hibernate.annotations.CascadeType.SAVE_UPDATE})
@Column( nullable = false  )
public Set<ObjectEntry> getObjectEntries() {
    return this.objectEntries;
}

and I put @cache both on ObjectEntry and on Object

@Cache(usage =  CacheConcurrencyStrategy.READ_WRITE)
public class Object extends HashCodeValidator {

@Cache(usage =  CacheConcurrencyStrategy.READ_WRITE)
public class ObjectEntry extends HashCodeValidator 

Do I still need to put @cache on getObjectEntries like this:

@org.hibernate.annotations.Cascade(
    {org.hibernate.annotations.CascadeType.SAVE_UPDATE})
@Column( nullable = false  )
@Cache(usage =  CacheConcurrencyStrategy.READ_WRITE)
public Set<ObjectEntry> getObjectEntries() {
    return this.objectEntries;
}

Do I need to define cache for each query if I specifically add

hibernate.cache.use_query_cache = true

?


Solution

  • (...) Do I still need to put @cache on getObjectEntries like this:

    Yes, you still have to cache a collection if you want to (that will be cached in a specific cache region).

    Do I need to define cache for each query if I specifically add hibernate.cache.use_query_cache = true

    From the reference documentation about the hibernate.cache.use_query_cache property (section 3.4. Optional configuration properties):

    Enables the query cache. Individual queries still have to be set cachable. e.g. true|false

    So, yes, you still have to set a query cachable (by calling setCacheable(true) on a query or criteria object) if you want to - which is IMO a good thing.