如何用Hibernate获取@ElementCollection的总和?

时间:2018-04-26 15:41:50

标签: hibernate spring-boot jpa java-ee jpql

我有一个包含以下内容的实体表:

@Entity 公共课邮报{

@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);
}

1 个答案:

答案 0 :(得分:0)

在JPQL中,您可以使用名为SIZE的函数来获取ElementCollection大小。

我完全不了解您希望如何查询数据,因此我将在示例实体结构中为您提供两个不同的可能用法示例。

获得N个投票最多的帖子

要获得N个最多投票的帖子,我们需要

  1. 按照 votesFor 集合的大小对帖子进行排序。
  2. 限制为N。
  3. 就像那样:

    select p from Post p order by SIZE(p.votesFor) desc limit :n
    

    其中:n 是查询中的某个参数

    获取至少N votesFor

    的帖子

    第二种可能的方法是查询至少有一些&#39; votesFor&#39;的帖子。要做到这一点,你只需要使用WHERE表达式,就像那样:

    select p from Post p where SIZE(p.votesFor) >= :n
    

    其中:n是您要寻找的最小票数。

    有关SIZE HERE

    等特殊运营商的更多信息
相关问题