How to get SELECT values and COUNT value with JPA GROUP BY?

前端 未结 1 342
孤城傲影
孤城傲影 2020-12-24 13:38

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          


        
相关标签:
1条回答
  • 2020-12-24 14:21

    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.

    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.

    Edit - Code Example:

    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();
    }
    
    0 讨论(0)
提交回复
热议问题