Ok, I found a solution but its really ugly:
Code:
package khdb.util;
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.*;
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;
}