【问题标题】:HQL checking if object contains all element s of requested setHQL 检查对象是否包含请求集合的所有元素
【发布时间】:2016-05-24 12:42:13
【问题描述】:

我有两个实体。例如,帖子和标签。 我必须编写一个方法,该方法只接受查询中提到的具有所有标签的帖子。

我试过了

@Query("select distinct p from posts p join p.tags t where t in ?1")
Page<Post> findDistinctByTagsIn(Set<Tag> tagSet, Pageable pageable);

但是,如果至少有一个标签包含在 tagSet 中,则需要 Post。

如何仅使用 HQL 和 JPA 存储库解决此问题?

更新:

@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name = "posts_tags", joinColumns = {
        @JoinColumn(name = "post_id", nullable = false, updatable = false)},
        inverseJoinColumns = {@JoinColumn(name = "tag_id")})
public Set<Tag> getTags() {
    return tags;
}

【问题讨论】:

  • 文章和标签在数据模型中是如何相互链接的?我们需要知道这些实体或基础表的相关部分。
  • @MickMnemonic,标签和帖子是多对多链接的

标签: java spring jpa hql spring-data-jpa


【解决方案1】:

加你Tag类下一个ManyToOne关系:

@Entity
public class Tag{
    ...

    private Post post;

    @ManyToOne
    @JoinTable(name = "posts_tags",
            joinColumns = {@JoinColumn(name = "tag_id")},
            inverseJoinColumns = {@JoinColumn(name = "post_id")})
    public Post getPost(){
        return post;
    }

    ...
}

让我们尝试构建查询。

我们不需要标签不在我们标签列表中的帖子。我们将在下一个查询中选择它们:

select t.post from Tag t where t not in (:tagSet) and t.post is not null

而且我们不需要根本没有任何标签的帖子。让我们也选择它们:

select p from Post p where p.tags is empty

现在让我们一起查询:

select p from Post p where 
p not in (select t.post from Tag t where t not in (:tagSet) and t.post is not null) 
and p not in (select p2 from Post p2 where p2.tags is empty)

你可以使用命名参数来绑定这个查询:

Page<Post> findDistinctByTagsIn(@Param("tagSet") Set<Tag> tagSet, Pageable pageable);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-03
    • 2021-06-20
    • 1970-01-01
    • 2017-10-23
    相关资源
    最近更新 更多