Convert Hql to Sql Query without hibernate_show_sq

2019-03-18 17:58发布

I am executing the following HQL and it is executing properly

String hql = "FROM Employee";
Query query = session.createQuery(hql);
List results = query.list();

Now i also want to log the sql generated at the backend in logs for support users , I want to make use of QueryTranslator please advise how can I generate the sql for corresponding HQL please advise how to achieve this.

标签: hibernate hql
4条回答
Evening l夕情丶
2楼-- · 2019-03-18 18:14

I found next solution on the web:

QueryTranslatorFactory translatorFactory = new ASTQueryTranslatorFactory();
SessionFactoryImplementor factory = (SessionFactoryImplementor) getSessionFactory();
QueryTranslator translator = translatorFactory.
        createQueryTranslator(hqlQueryText, hqlQueryText, Collections.EMPTY_MAP, factory);
translator.compile(Collections.EMPTY_MAP, false);
translator.getSQLString(); 

Source: http://narcanti.keyboardsamurais.de/hibernate-hql-to-sql-translation.html

查看更多
Ridiculous、
3楼-- · 2019-03-18 18:20

you can get the Query out by using the unwrap method.

String queryString = query.unwrap(org.hibernate.Query.class).getQueryString();
查看更多
淡お忘
4楼-- · 2019-03-18 18:37

I believe you want a combination of the top 2 answers

  String hqlQueryString = query.unwrap(org.hibernate.Query.class).getQueryString();
  ASTQueryTranslatorFactory queryTranslatorFactory = new ASTQueryTranslatorFactory();
  SessionImplementor hibernateSession = em.unwrap(SessionImplementor.class);
  QueryTranslator queryTranslator = queryTranslatorFactory.createQueryTranslator("", hqlQueryString, java.util.Collections.EMPTY_MAP, hibernateSession.getFactory());
  queryTranslator.compile(java.util.Collections.EMPTY_MAP, false);
  String sqlQueryString = queryTranslator.getSQLString();
查看更多
混吃等死
5楼-- · 2019-03-18 18:39

You can use hibernate QueryTranslator:

String hqlQueryString = hqlQuery.getQueryString();
ASTQueryTranslatorFactory queryTranslatorFactory = new ASTQueryTranslatorFactory();
SessionImplementor hibernateSession = entityManager.unwrap(SessionImplementor.class);
QueryTranslator queryTranslator = queryTranslatorFactory.createQueryTranslator("", hqlQueryString, java.util.Collections.EMPTY_MAP, hibernateSession.getFactory());
queryTranslator.compile(java.util.Collections.EMPTY_MAP, false);
String sqlQueryString = queryTranslator.getSQLString();
查看更多
登录 后发表回答