Grails Groovy SessionFactory EnityKey SessionStatistics | Grails Get SQL Table Name From Domain Class | Grails Get SQL Table Field Name From Domain Class.
c
import org.hibernate.SessionFactory
import grails.util.Holders
import org.hibernate.engine.spi.EntityKey import org.hibernate.stat.SessionStatistics /** * Created by pritom on 27/07/2017. */ class HibernateSessionUtil { private static SessionFactory _sessionFactory public static void main(String[] args) { def domainInstance = "DomainClass".proxy(100L) checkIfObjectExistsInSession(domainInstance) } static void evictAllEntities() { SessionStatistics sessionStatistics = sessionFactory.currentSession.getStatistics() sessionStatistics.getEntityKeys().asList().each { EntityKey entityKey -> evict(entityKey.persisterClass.proxy(entityKey.identifier.toString().toLong())) } } static void evict(def instance) { sessionFactory.currentSession.evict(instance) } 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 String getTableFieldName(Class clazz, String fieldName) { return sessionFactory.getClassMetadata(clazz).propertyMapping.getColumnNames(fieldName)[0] } static String getTableName(Class clazz) { return sessionFactory.getClassMetadata(clazz).getTableName() } static boolean flushAndClearCache() { try { sessionFactory.currentSession.flush() sessionFactory.currentSession.clear() sessionFactory.getCache().evictEntityRegions() sessionFactory.getCache().evictCollectionRegions() sessionFactory.getCache().evictDefaultQueryRegion() sessionFactory.getCache().evictQueryRegions() return true } catch (Exception ex) { ex.printStackTrace() return false } } static SessionFactory getSessionFactory() { _sessionFactory = _sessionFactory ?: (_sessionFactory = Holders.applicationContext.getBean(SessionFactory)) } static { EntityKey.metaClass.getPersisterClass = { return persister.entityTuplizer.mappedClass } } }
c
No comments:
Post a Comment