如何使用COUNT
和GROUP 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,但也失败了
答案 0 :(得分:1)
一种解决方法是使用构造函数语法,如下所示:
SELECT NEW org.apache.commons.lang3.tuple.ImmutablePair(c.parentId, COUNT(c.id)) FROM ...
当然,您可以使用任何其他类代替ImmutablePair
(例如Map.MapEntry
的具体实现)。然后,您将结果声明为List<ImmutablePair>
,并将结果收集到服务方法中的地图中。