【问题标题】:QueryDsl - Exclude results based on nested array contentsQueryDsl - 根据嵌套数组内容排除结果
【发布时间】:2021-09-01 06:52:01
【问题描述】:

我正在尝试使用 QueryDsl 获取所有不包含特定类别的帖子

我的模型定义为:

发帖

@QueryEntity
@Table(name = "posts")
public class PostEntity implements {
    @Id
    @Column(name = "id")
    private String id;

    @OneToMany
    @JoinTable(
            name = "post_categories",
            joinColumns = @JoinColumn(name = "post_id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "category_id", referencedColumnName = "id")
    )
    private List<CategoryEntity> categories;
}

类别

@QueryEntity
@Table(name = "categories")
public class CategoryEntity {
    @Id
    @Column
    private String id;

}

(为简洁起见,省略了一些 Lombok 注释)

两者通过post_categories连接表关联,以类别标记帖子。

我尝试使用与此类似的查询来排除归类为 news 的帖子:

var query = QPostEntity
                .postEntity
                .categories.any().id.notIn("news");

但是,它仍然返回该类别的帖子 - 我让它正常工作的唯一方法是在 notIn 语句中包含所有帖子类别。

问题:如何查询不包含特定类别的帖子?


更新 #1

似乎上面的查询生成的子查询类似于

where exists(
    select 1 from post_categories where category_id not in ('news')
    ) 

其中还包括所有其他类别的帖子。我发现以下查询确实产生了正确的结果(not 移动到 exists 语句之前):

where not exists(
    select 1 from post_categories where category_id in ('news')
    )

这可以通过将 querydsl 重写为:

.categories.any().id.in("news").not();

但是,这似乎很令人困惑。有更好的方法吗?

【问题讨论】:

  • 有些不清楚...新闻不应该是类别中“名称”列的值吗?
  • 我认为这是正确的@Lorelorelore - 在这种情况下news 是主键,它是一个字符串。我将从示例中删除 name 以使其更明显。
  • 好吧,这只是为了我的理解

标签: java spring-boot jpa querydsl


【解决方案1】:

我会尝试使用子查询来解决这个问题。您可以尝试以下方法吗?

SubQueryExpression<String> subquery = JPAExpressions.select(QCategoryEntity.categoryEntity.id)
                .from(QCategoryEntity.categoryEntity)
                .where(CategoryEntity.categoryEntity.eq("news"));

        return new JPAQueryFactory(em)
                .select(QPostEntity.postEntity)
                .from(QPostEntity.postEntity)
                .innerJoin(QPostEntity.postEntity.categories)
                .where(QCategoryEntity.categoryEntity.id.notIn(subquery));

您可能没有使用JPAQueryFactory...如果没有,您能否分享一下您实际执行查询的方式?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 2018-11-30
    • 2022-08-11
    • 1970-01-01
    • 2017-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多