如何使用JPA GROUP BY获取SELECT值和COUNT值? [英] How to get SELECT values and COUNT value with JPA GROUP BY?

查看:211
本文介绍了如何使用JPA GROUP BY获取SELECT值和COUNT值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的实体以Man的身份获得,则它具有名称,id属性,通过JPA,我如何获得像该查询一样的检索结果,

If my entity is get as a Man, it have name, id properties, with JPA how I get retrieve result like this query,

entityManager.createQuery("SELECT m.name AS name, COUNT(m) AS total FROM Man AS m GROUP BY m.name ORDER BY m.name ASC");

是否可以通过JPA使用org.springframework.jdbc.core.RowMapper?

Is there any way to use org.springframework.jdbc.core.RowMapper with JPA?

推荐答案

执行此查询时,您将检索到Object[]列表,而不是像通常那样直接获取对象列表.

When you execute this query, instead of getting directly a list of objects like usual, you'll retrieve a list of Object[].

对于您检索的每个数组,第一个元素将是行的名称,第二个是计数.

For each array you retrieve, the first element will be the name of the row, the second the count.

我认为您不能在JPA中使用RowMapper. RowMapper来自Spring,它与JPA不同.也许某些JPA实现允许这样做,但是我认为这样做是不明智的.

I don't think you can use a RowMapper with JPA. RowMapper comes from Spring, which is not the same framework as JPA. Maybe some JPA implementation allow this, but I don't think it is wise to do so.

编辑-代码示例:

List<Object[]> results = entityManager
        .createQuery("SELECT m.name AS name, COUNT(m) AS total FROM Man AS m GROUP BY m.name ORDER BY m.name ASC");
        .getResultList();
for (Object[] result : results) {
    String name = (String) result[0];
    int count = ((Number) result[1]).intValue();
}

这篇关于如何使用JPA GROUP BY获取SELECT值和COUNT值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆