Last active
January 11, 2022 16:28
-
-
Save brunocribeiro/cab232943752d344ed05 to your computer and use it in GitHub Desktop.
Utility method to get SQL from Hibernate Criteria
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
import lombok.AccessLevel; | |
import lombok.NoArgsConstructor; | |
import lombok.extern.slf4j.Slf4j; | |
import org.hibernate.Criteria; | |
import org.hibernate.engine.spi.SessionFactoryImplementor; | |
import org.hibernate.internal.CriteriaImpl; | |
import org.hibernate.internal.SessionImpl; | |
import org.hibernate.loader.OuterJoinLoader; | |
import org.hibernate.loader.criteria.CriteriaLoader; | |
import org.hibernate.persister.entity.OuterJoinLoadable; | |
import java.lang.reflect.Field; | |
@Slf4j | |
@NoArgsConstructor(access = AccessLevel.PRIVATE) | |
public final class CriteriaUtils { | |
public static void logSQLFromCriteria(final Criteria criteria) { | |
final CriteriaImpl c = (CriteriaImpl) criteria; | |
final SessionImpl s = (SessionImpl) c.getSession(); | |
final SessionFactoryImplementor factory = s.getSessionFactory(); | |
final String[] implementors = factory.getImplementors(c.getEntityOrClassName()); | |
final CriteriaLoader loader = new CriteriaLoader((OuterJoinLoadable) | |
factory.getEntityPersister(implementors[0]), factory, c, implementors[0], | |
s.getLoadQueryInfluencers()); | |
try { | |
final Field f = OuterJoinLoader.class.getDeclaredField("sql"); | |
f.setAccessible(true); | |
log.debug((String) f.get(loader)); | |
} catch (final NoSuchFieldException | IllegalAccessException e) { | |
log.error(e.getMessage(), e); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment