4

考虑以下实体:

@Entity
public class User {
    private int id;
    private String name;
    private String family;
    //getters and setters
}

和 sql:

select * 
from (select row_.*, first_Value(rownum) over (order by rownum desc) countـ
      from (select * from user) row_)

您可能会猜到 sql 的结果集由四列组成:

id, name, family, countـ

我通过以下方式检索用户表记录作为用户列表:

String myQuery = "select * from (select row_.*, first_Value(rownum) over (order by rownum desc) count_
      from (select * from user) row_)"
Query query = entityManager.createNativeQuery(myQuery, User.class);
List<User> users = query.getResultList();

现在的问题是,我如何仅通过调用 getResultList() 或任何其他休眠等效项来检索用户列表并计算值?

我使用 Oracle 11g 和 Jpa (Hibernate implementation 3.6)

提前致谢。

4

1 回答 1

2

我认为“计数”是一个保留字。我会像这样重新组织您的查询:

String myQuery = "SELECT "
        + "id, "
        + "name, "
        + "family, "
        + "cnt "
        + "FROM ("
            + "SELECT "
            + "user.*, "
            + "first_Value(rownum) over (order by rownum desc) AS cnt "
            + "FROM "
            + "user "
        + ")";
    Query query = entityManager.createNativeQuery(myQuery);
    List<Object[]> resultList = query.getResultList();

当然,您也可以使用 * 代替“id、name、family、cnt”。

于 2013-04-21T15:48:14.507 回答