如何使用and编写JPQL查询并获得结果?COUNT
GROUP BY
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 ...
当然,您可以使用任何其他类来代替ImmutablePair
(例如 的具体实现Map.MapEntry
)。然后,您将结果声明为 aList<ImmutablePair>
并将结果收集到您的服务方法中的地图中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句