Skip to content

Instantly share code, notes, and snippets.

@gtors
Created July 27, 2016 12:26
Show Gist options
  • Save gtors/726ffcef60e95ce21d3fa8c8383860c3 to your computer and use it in GitHub Desktop.
Save gtors/726ffcef60e95ce21d3fa8c8383860c3 to your computer and use it in GitHub Desktop.
Utility class for extraction SQL statement from the Grails Detached Criteria (Hibernate)
import grails.gorm.DetachedCriteria
import grails.util.Holders
import org.codehaus.groovy.grails.orm.hibernate.query.HibernateQuery
import org.grails.datastore.gorm.finders.DynamicFinder
import org.hibernate.engine.spi.SessionFactoryImplementor
import org.hibernate.internal.CriteriaImpl
import org.hibernate.internal.SessionImpl
import org.hibernate.loader.criteria.CriteriaLoader
import org.hibernate.persister.entity.OuterJoinLoadable
class SqlUtils {
static String extractSqlStatement(DetachedCriteria dc) {
def factory = Holders.applicationContext.getBean('sessionFactory') as SessionFactoryImplementor
def entityName = (dc.persistentClass as Class).name
def session = factory.currentSession as SessionImpl
def criteria = session.createCriteria(dc.persistentClass as Class) as CriteriaImpl
DynamicFinder.applyDetachedCriteria(new HibernateQuery(criteria, null, dc.persistentEntity), dc)
new CriteriaLoader(
factory.getEntityPersister(entityName) as OuterJoinLoadable,
factory,
criteria,
entityName,
session.getLoadQueryInfluencers()
).getSQLString()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment