如何使用`COUNT`和`GROUP BY`编写JPQL查询

时间:2017-12-15 14:35:44

标签: jpa spring-data-jpa jpql

如何使用COUNTGROUP BY撰写 JPQL 查询,并将结果设为Map<Integer,Integer>

public class CommentEntity {

 private int id;

 private int parentId;

 private EntityParentType parentType;

 private Long replyCounts;

 private String author;

 private String comment;

}

public enum EntityParentType {

 PERSON,
 EVENT,
 COMMENT;

}

我写了 MySQL 查询,这很好用:

SELECT parent_id, COUNT(*) FROM comment AS c WHERE c.parent_type = 2 AND c.parent_id IN (64,65) GROUP BY parent_id

enter image description here

JPQL 查询失败:

@Repository
@Transactional(readOnly = true)
public interface CommentRepository extends JpaRepository<CommentEntity, Integer> {

 @Query(value = "SELECT c.parentId, COUNT(c.id) FROM CommentEntity AS c WHERE c.parentType = ?1 AND c.parentId IN (?2) GROUP BY c.parentId")
 Map<Integer, Integer> findReplyCountByParentIds(EntityParentType entityParentType, List<Integer> ids);

}

Method threw 'org.springframework.dao.IncorrectResultSizeDataAccessException' exception.
result returns more than one elements
下面的

也是失败的:

@Query(value = "SELECT c.parentId, COUNT (c.id) FROM CommentEntity AS c WHERE c.parentType = ?1 AND c.parentId IN (?2) GROUP BY c.parentId")
 List<Map<Integer, Integer>> findReplyCountByParentIds(EntityParentType entityParentType, List<Integer> ids);

Method threw 'org.springframework.dao.InvalidDataAccessApiUsageException' exception.
No aliases found in result tuple! Make sure your query defines aliases!

我尝试将pacakge添加到CommentEntity,但也失败了

1 个答案:

答案 0 :(得分:1)

一种解决方法是使用构造函数语法,如下所示:

SELECT NEW org.apache.commons.lang3.tuple.ImmutablePair(c.parentId, COUNT(c.id)) FROM ...

当然,您可以使用任何其他类代替ImmutablePair(例如Map.MapEntry的具体实现)。然后,您将结果声明为List<ImmutablePair>,并将结果收集到服务方法中的地图中。