What is the best caching policy in Hibernate\Grails. Cache all entities and queries or not and how to find best solution ?
Here my hibernate config.
hibernate {
cache.use_second_level_cache = true
cache.use_query_cache = true
cache.provider_class = 'org.hibernate.cache.EhCacheProvider'
connection.useUnicode = true
connection.characterEncoding = 'UTF-8'
connection.provider_class = 'org.hibernate.connection.C3P0ConnectionProvider'
dialect = 'org.hibernate.dialect.MySQL5InnoDBDialect'
order_updates = true
c3p0.min_size = 5
c3p0.max_size = 20
c3p0.max_statements = 20 * 10
c3p0.idle_test_period = 15 * 60
}
Ehcache config
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
maxElementsOnDisk="10000000"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
diskSpoolBufferSizeMB="100"
memoryStoreEvictionPolicy="LRU"
/>
<cache
name="org.hibernate.cache.StandardQueryCache"
maxElementsInMemory="50"
eternal="false"
timeToLiveSeconds="120"
overflowToDisk="true"
/>
Hibernate caching acts as a layer between the actual database and your application. It reduces the time taken to obtain the required data — as it fetches from memory instead of directly hitting the database. It is very useful when you need to fetch the same kind of data multiple times.
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.
Hibernate also implements a cache for query resultsets that integrates closely with the second-level cache. This is an optional feature and requires two additional physical cache regions that hold the cached query results and the timestamps when a table was last updated.
Hibernate 2nd level cache is best suitable for data that rarely or never changes. However since hibernate provides a generalized caching provider implemented by multiple caching solutions, it limits usability of features provided by caching solutions.
The best caching policy is: no caching. Seriously, caching (and any optimization) should be done only to solve an existing problem. If you don't have performance problems, don't use caching. If you do have performance problems, then apply this simple 5-step procedure for solving performance problems:
Note that if you don't understand how the caching works in Hibernate, you can end up having poor performance, instead of improving it. Also, even if you understand how caching works in Hibernate, there may be other effects influencing the performance, causing a database roundtrip to be faster than looking up the cache. That's why you should measure before and after doing "improvements".
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