【问题标题】:Is there a way to write this SQL in HQL?有没有办法在 HQL 中编写此 SQL?
【发布时间】:2018-08-09 00:59:44
【问题描述】:

我需要使用 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 正确编写本文中的第一个查询?

【问题讨论】:

    标签: mysql sql hibernate hql


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      您可以通过使用持久性 API 来实现这一点 "entityManager.createNativeQuery" 或 "entityManager.createQuery" as

      String queryString = "SELECT t.atrib2, MY_FUNC(attrib1), MY_FUNC(attrib2), o.atrib1 FROM (选择 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"; javax.persistence.Query 查询 = entityManager.createNativeQuery(queryString);

      【讨论】:

        猜你喜欢
        • 2014-12-26
        • 1970-01-01
        • 2012-09-14
        • 1970-01-01
        • 2019-08-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多