考虑以下实体:
@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()或任何其他hibernate等效项来计算值?
我使用Oracle 11g和Jpa(Hibernate实现3.6)
提前致谢。
答案 0 :(得分: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”。