Created
July 23, 2015 06:48
-
-
Save ramsrib/db6ad31eecec0100eded to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Testing the jpa (hibernate) second level cache by running different way of findById method | |
public UserSession findById(String id) { | |
System.out.println("Running UserSession.findById"); | |
Session session = getEntityManager().unwrap(Session.class); | |
SessionFactory sessionFactory = session.getSessionFactory(); | |
String rName = "test.ear/model.jar#model.com.test.app.authentication.model.UserSession"; | |
long oldMissCount = sessionFactory.getStatistics().getSecondLevelCacheStatistics(rName).getMissCount(); | |
long oldHitCount = sessionFactory.getStatistics().getSecondLevelCacheStatistics(rName).getHitCount(); | |
// the following line doesn't fetch from second level cache | |
// TypedQuery<UserSession> query = getEntityManager().createNamedQuery(UserSession.BY_ID, UserSession.class); | |
// query.setParameter("id", id); | |
// UserSession userSession = query.getSingleResult(); | |
// this will fetch from second level cache | |
UserSession userSession = getEntityManager().find(id); | |
long newMissCount = sessionFactory.getStatistics().getSecondLevelCacheStatistics(rName).getMissCount(); | |
long newHitCount = sessionFactory.getStatistics().getSecondLevelCacheStatistics(rName).getHitCount(); | |
System.out.println("old hit count : " + oldHitCount + ", old miss count : " + oldMissCount); | |
System.out.println("new hit count : " + newHitCount + ", new miss count : " + newMissCount); | |
if(oldHitCount+1 == newHitCount && oldMissCount+1 == newMissCount) { | |
System.out.println("Came from DB"); | |
} else if(oldHitCount+1 == newHitCount && oldMissCount == newMissCount) { | |
System.out.println("Came from CACHE"); | |
} | |
System.out.println("Entries in memory : " + sessionFactory.getStatistics().getSecondLevelCacheStatistics(rName).getEntries()); | |
sessionFactory.getStatistics().logSummary(); | |
return userSession; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice one !
you can add (kotlin style) :
it's not obvious from where your
getEntityManager
is coming from.