Hibernate use first & second level cache to store database data fetch from database and actually its Hibernate Session. So when your read data from database it stores in Hibernate Session. There is a separate Hibernate Session for each request. Sometimes we need to identify if any object exists in session or not. Below is a simple code snippet to determine if any object exists in current Hibernate Session or not. The most important thing is that you must use proxy to reference the object to check.
package com.pkm
import grails.util.Holders
import org.hibernate.SessionFactory
import org.hibernate.engine.spi.EntityKey
import org.hibernate.stat.SessionStatistics
/**
* Created by pritom on 15/03/2017.
* Session.html#getStatistics
* SessionStatistics.html#getEntityKeys
*/
class HibernateSessionUtil {
private static SessionFactory sessionFactory
public static void main(String[] args) {
def domainInstance = "DomainClass".proxy(100L)
checkIfObjectExistsInSession(domainInstance)
}
static Boolean checkIfObjectExistsInSession(def domainInstance) {
SessionStatistics sessionStatistics = sessionFactory.currentSession.getStatistics()
println("Total ${sessionStatistics.getEntityKeys().asList().size()} Object Exists in Session")
Boolean exists = false
sessionStatistics.getEntityKeys().asList().find { EntityKey entityKey ->
println("EntityName=${entityKey.entityName},EntityId=${entityKey.identifier.toString()}")
if (domainInstance.class.canonicalName.equals(entityKey.entityName) &&
domainInstance.id.toString().equals(entityKey.identifier.toString())) {
exists = true
}
}
return exists
}
static {
sessionFactory = sessionFactory ?: (sessionFactory = getBean(SessionFactory))
}
static <T> T getBean(Class<T> requiredType) {
try {
return Holders.applicationContext.getBean(requiredType)
}
catch (Exception e) {
return null
}
}
}
No comments:
Post a Comment