QueryDsl BooleanBuilder: 如何创建一个比较列表内容的谓词?

huangapple go评论91阅读模式
英文:

QueryDsl BooleanBuilder: How to create a predicate that compares contents of list?

问题

我有一个简单的例子:查找所有具有优先级大于1且活动状态为true的项目。

项目有一个类别列表,每个类别都有一个名为优先级的整数字段。
我正在尝试做类似以下的事情:

builder = new BooleanBuilder();
Predicate predicate = builder.and(item.categories.any(category.priority.goe(1).and(category.active.eq(true))));
Iterable<Item> iterable = itemRepository.findAll(predicate);

但我找不到正确的方法要怎么用?请问有人可以建议吗?

英文:

I have simple example: to find all items that has a category with priority > 1 and active = true .

Item has a list of categories, each has an int field called priority.
I'm trying to do something like:

builder = new BooleanBuilder();
Predicate predicate = builder.and(item.categories.any(category.priority.goe(1).and(category.active.eq(true))));
Iterable&lt;Item&gt; iterable = itemRepository.findAll(predicate);

but i cannot find the right method to use? Can someone pls advise?

答案1

得分: 1

你可以像下面这样使用 BooleanExpression -

public List<Item> getItems() {
    QItem item = QItem.item;
    QCategory category = QCategory.category;
    BooleanExpression booleanExpression = item.categories.contains(
        JPAExpressions.selectFrom(category).
          where(category.item.eq(item).
           and(category.priority.eq(1000)
                   .and(category.active.eq(true)))));
    return itemRepository.findAll(booleanExpression);
}

这个在版本 4.3.1 下对我有效,但在 4.2.1 下无效。请查看这个使用Spring Boot的示例

英文:

You can use BooleanExpression like below -

public List&lt;Item&gt; getItems() {
		QItem item = QItem.item;
		QCategory category = QCategory.category;
		BooleanExpression booleanExpression = item.categories.contains(
		        JPAExpressions.selectFrom(category).
		          where(category.item.eq(item).
		           and(category.priority.eq(1000)
		        		   .and(category.active.eq(true)))));
		return (List&lt;Item&gt;) itemRepository.findAll(booleanExpression);
	}

This worked for me with version 4.3.1 but not with 4.2.1. Please check this example using springboot.

huangapple
  • 本文由 发表于 2020年8月12日 12:32:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/63369803.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定