In the previous post we saw the GET and IGNORE values for CacheMode. The other values are PUT and REFRESH. Consider the below code:
publicstatic void testPutMode() {In the PUT mode, the session will add records to the second level cache. However it will not read any records from the cache. As the second session uses the PUT CacheMode it does nor read the record with id 1 from the cache. It fires three select queries for all three records, adding two of them to the cache. The output from above method is :
Statistics statistics = sessionFactory.getStatistics();
Session session1 = sessionFactory.openSession();
System.out.println("Cache Put Count : "
+ statistics.getSecondLevelCachePutCount());
session1.get(BookType.class, 1);
System.out.println("Cache Put Count : "
+ statistics.getSecondLevelCachePutCount());
session1.close();
System.out.println("Running in PUT mode");
Session session2 = sessionFactory.openSession();
session2.setCacheMode(CacheMode.PUT);
session2.get(BookType.class, 1);
session2.get(BookType.class, 2);
session2.get(BookType.class, 3);
System.out.println("Cache Put Count : "
+ statistics.getSecondLevelCachePutCount());
System.out.println("Cache Hit Count : "
+ statistics.getSecondLevelCacheHitCount());
session2.close();
}
Cache Put Count : 0
Hibernate:
/* load com.object.cache.BookType */
selectThe other CacheMode is REFRESH. This has the same behavior as PUT (Or does it ?) From the Hibernate docs:
booktype0_.ID as ID0_0_,
booktype0_.NAME as NAME0_0_
from
BOOK_TYPE_MASTER booktype0_
where
booktype0_.ID=?
Cache Put Count : 1
Running in PUT mode
Hibernate:
/* load com.object.cache.BookType */
select
booktype0_.ID as ID0_0_,
booktype0_.NAME as NAME0_0_
from
BOOK_TYPE_MASTER booktype0_
where
booktype0_.ID=?
Hibernate:
/* load com.object.cache.BookType */
select
booktype0_.ID as ID0_0_,
booktype0_.NAME as NAME0_0_
from
BOOK_TYPE_MASTER booktype0_
where
booktype0_.ID=?
Hibernate:
/* load com.object.cache.BookType */
select
booktype0_.ID as ID0_0_,
booktype0_.NAME as NAME0_0_
from
BOOK_TYPE_MASTER booktype0_
where
booktype0_.ID=?
Cache Put Count : 3
Cache Hit Count : 0
CacheMode.PUT: will write items to the second-level cache.I tested the above method for Refresh but did not find any difference in the result. I found one link that seemed to add something to this explanation.
Do not read from the second-level cache
CacheMode.REFRESH: will write items to the second-level cache.
Do not read from the second-level cache.
Bypass the effect of hibernate.cache.use_minimal_puts forcing
a refresh of the second-level cache for all items read from the database
What is the default value for CacheMode ?
publicstatic void testDefaultCacheMode() {The output is :
Session session = sessionFactory.openSession();
System.out.println(session.getCacheMode());
}
NORMAL