有没有办法在HQL中编写这个SQL?

时间:2018-03-01 02:10:04

标签: mysql sql hibernate hql

我需要使用Hibernate(HQL)在MySQL中运行此查询:

SELECT t.atrib2, MY_FUNC(attrib1), MY_FUNC(attrib2), o.atrib1
       FROM (SELECT t.atrib1, t.atrib2, t.atrib3,o.atrib1
             FROM myTable t JOIN otherTable o
                  ON O.ID = T.O_ID   
                  ORDER BY creationDate
                  LIMIT 0, 100000) t;

我不能像这样使用SELECT:

SELECT t.atrib2, MY_FUNC(attrib1), MY_FUNC(attrib2), o.atrib1
       FROM myTable t JOIN otherTable o
       ON o.ID = t.o_ID   
       ORDER BY creationDate
       LIMIT 0, 100000;

因为MySQL在加入表时将函数MY_FUNC应用于所有行,并且这变得太慢,就像在线程上一样: MySQL very slow query with custom function in spite of LIMIT

如何使用HQL在本文中正确编写第一个查询?

2 个答案:

答案 0 :(得分:0)

是的,在hibernate中,您可以使用SQLQuery编写SQL查询而不是HQL。 像:

 String sql = "select * from User" ;
  SQLQuery query = session.CreateSQLQuery(sql);

答案 1 :(得分:0)

你可以通过使用持久性Api来实现这一点 " entityManager.createNativeQuery "或" entityManager.createQuery "如

String queryString =" SELECT t.atrib2,MY_FUNC(attrib1),MY_FUNC(attrib2),o.atrib1 FROM(SELECT t.atrib1,t.atrib2,t.atrib3,o.atrib1 FROM myTable t JOIN otherTable o ON O.ID = T.O_ID ORDER BY creationDate LIMIT 0,100000)t &#34 ;; javax.persistence.Query query = entityManager.createNativeQuery(queryString);