Skip to content

Instantly share code, notes, and snippets.

@netstart
Last active August 29, 2015 14:20
Show Gist options
  • Save netstart/b68723818a734d091708 to your computer and use it in GitHub Desktop.
Save netstart/b68723818a734d091708 to your computer and use it in GitHub Desktop.
import java.lang.reflect.*;
import java.util.*;
import java.util.Collections;
import org.hibernate.*;
import org.hibernate.engine.*;
import org.hibernate.hql.*;
import org.hibernate.hql.ast.*;
import org.hibernate.impl.*;
import org.hibernate.loader.*;
import org.hibernate.loader.criteria.*;
import org.hibernate.persister.entity.*;
/**
* toSql by Criteria and HQL
*/
public class HibernateUtil {
public static String toSql(Session session, Criteria criteria){
try{
CriteriaImpl c = (CriteriaImpl) criteria;
SessionImpl s = (SessionImpl)c.getSession();
SessionFactoryImplementor factory = (SessionFactoryImplementor)s.getSessionFactory();
String[] implementors = factory.getImplementors( c.getEntityOrClassName() );
CriteriaLoader loader = new CriteriaLoader((OuterJoinLoadable)factory.getEntityPersister(implementors[0]),
factory, c, implementors[0], s.getLoadQueryInfluencers());
Field f = OuterJoinLoader.class.getDeclaredField("sql");
f.setAccessible(true);
return (String) f.get(loader);
}
catch(Exception e){
throw new RuntimeException(e);
}
}
public static String toSql(Session session, String hqlQueryText){
if (hqlQueryText!=null && hqlQueryText.trim().length()>0){
final QueryTranslatorFactory translatorFactory = new ASTQueryTranslatorFactory();
final SessionFactoryImplementor factory =
(SessionFactoryImplementor) session.getSessionFactory();
final QueryTranslator translator = translatorFactory.
createQueryTranslator(
hqlQueryText,
hqlQueryText,
java.util.Collections.EMPTY_MAP, factory
);
translator.compile(Collections.EMPTY_MAP, false);
return translator.getSQLString();
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment