【发布时间】:2018-10-07 09:29:12
【问题描述】:
我有一个包含以下内容的实体表:
@实体 公共类帖子{
@Id
@GeneratedValue
private Long id;
@NotBlank
@Size(min = 1, max = 2014)
private String text;
@NotNull
@Temporal(TemporalType.TIMESTAMP)
private Date created;
@NotNull
@ManyToOne
private User author;
@ElementCollection(fetch = FetchType.EAGER)
private Set<String> votesFor;
@ElementCollection(fetch = FetchType.EAGER)
private Set<String> againstFor;
@OneToMany(mappedBy = "post", cascade = CascadeType.REMOVE)
private List<Comment> comments;
public Post() {
votesFor = new HashSet<>();
againstFor = new HashSet<>();
comments = new ArrayList<>();
}
我想创建一个 TypedQuery,我可以在其中获得投票最多的帖子。 我通过以下代码在@ElementCollection 中添加投票。
我如何对@ElementCollection 求和,然后返回一个列表,其中包含在开始时具有最高票数的帖子并以较少票数停止?
public void votesFor(String userId, long postId) {
Post post = em.find(Post.class, postId);
if(post == null) {
throw new IllegalArgumentException("Post not exists: " + postId);
}
if(post.getVotesFor().contains(userId)) {
throw new IllegalArgumentException("User " + userId + " have already voted");
}
post.getVotesFor().add(userId);
post.getAgainstFor().remove(userId);
}
【问题讨论】:
-
不清楚你在问什么。
标签: hibernate spring-boot jpa jakarta-ee jpql