Skip to content

Instantly share code, notes, and snippets.

@ramsrib
Created July 23, 2015 06:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ramsrib/db6ad31eecec0100eded to your computer and use it in GitHub Desktop.
Save ramsrib/db6ad31eecec0100eded to your computer and use it in GitHub Desktop.
// 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;
}
@neogeogre
Copy link

neogeogre commented Apr 22, 2021

nice one !
you can add (kotlin style) :

@Autowired
lateinit var entityManager: EntityManager

it's not obvious from where your getEntityManager is coming from.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment