考虑以下实体:
@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)
提前致谢.
最佳答案 我认为“计数”是一个保留字.我会重新组织你的查询,如下所示:
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”.