Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HQL to SQL in Java 5

Is it possible to translate in run time, the HSQL statement to SQL using EntityManager?

I've found this solution but I don't have the sessionFactory, I have EntityManager

protected String toSql(String hqlQueryText) {
    if (sessionFactory != null && hqlQueryText != null && hqlQueryText.trim().length() > 0) {
        final QueryTranslatorFactory translatorFactory = new ASTQueryTranslatorFactory();
        final SessionFactoryImplementor factory = (SessionFactoryImplementor) sessionFactory;
        final QueryTranslator translator = translatorFactory.createQueryTranslator(hqlQueryText, hqlQueryText,
        Collections.EMPTY_MAP, factory);
        translator.compile(Collections.EMPTY_MAP, false);
        return translator.getSQLString();
        }
    return null;
}
like image 254
Javi Pedrera Avatar asked Nov 03 '22 19:11

Javi Pedrera


1 Answers

If you got the EntityManager you can use the following piece of code to get the SessionFactory:

EntityManager em = ...
SessionFactory sf = ((EntityManagerFactoryImpl)em.getEntityManagerFactory()).getSessionFactory();
like image 123
MicSim Avatar answered Nov 09 '22 10:11

MicSim