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

How to write JPQL query with `COUNT` and `GROUP BY`

如何使用 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

但是 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,但还是失败了

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

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

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