【问题标题】:QueryDSL AND/ OR Operator Not Working with BooleanExpressionQueryDSL AND/ OR 运算符不使用 BooleanExpression
【发布时间】:2014-05-07 05:33:28
【问题描述】:

我们正在对实体进行搜索,我们正在使用 Query DSL。

表结构如下

TableA : shop -> has manytoOne relationship to TableB : Discount

我们需要建立一个谓词来返回所有没有打折的商店
Sale 也就是打折的 Sale 。

我们使用 MySQL 数据库和 JPA 作为我们的持久性框架。

场景是我们正在执行搜索,搜索应该找到所有没有折扣的商店和批准折扣的商店。

以下是我们目前拥有的布尔表达式。

BooleanExpression A = shop.id.eq(SomeId);
BooleanExpression B = shop.name.eq(SomeName)
BooleanExpression C = shop.discount.isNotNull;
BooleanExpression D = shop.discount.isNull;
BooleanExpression E = shop.disccount.approved.eq(SomeValue)

现在我们需要构建查询来获取所有没有折扣的商店,以及所有有折扣和批准的商店。

我们尝试了谓词

A
.and(B)
.and(D .or(C.and(D).and(E))
)

我们希望查询是

where shop.id=#someid and shop.name = 'some name' and (shop.discount is Null Or (shop.discount is not null and shop.approved='#some Value'))

但是生成的查询是

where  shop.id=`#someid` and shop.name = `'some name'` and (shop.discount is Null Or shop.discount is not null and shop.approved='`#some Value`')

我们没有用这个谓词得到正确的结果集,

有什么方法可以重写谓词以使其按预期工作?请帮助我提出建议。

谢谢 萨拉瓦娜。

【问题讨论】:

    标签: querydsl


    【解决方案1】:
    A.and(B).and(D .or(C.and(D).and(E)))
    

    等价于

    A and B and (D or C and D and E)
    

    有关 MySQL 运算符优先级的信息,请参见此处https://dev.mysql.com/doc/refman/5.0/en/operator-precedence.html

    关于你的例子,这应该可以工作

    shop.discount.isNull()
    .or(shop.discount.isNotNull()
        .and(shop.discount.approved.eq(SomeValue)))
    

    【讨论】:

    • 谢谢蒂莫,我们是否可以使用布尔表达式来实现要求,或者我们必须从不同的方向思考,比如为 2 个不同的条件设置 2 个谓词?喜欢一买不打折,一买打折?
    • 感谢 Timo 的建议,但我们仍然遇到同样的问题
    • Shop.id.eq(somevalue) .and Shop.sale.isNotNull .and (shop.discount.isNull() .or(shop.discount.isNotNull() .and(shop.discount.approved.eq(SomeValue))) 将等同于 Shop.id.eq(somevalue) .and Shop.sale.isNotNull .and (shop.discount.isNull() .or shop.discount.isNotNull() .and shop.discount.approved.eq(SomeValue)) 这不是我想要的,而是我需要的是Shop.id.eq(somevalue) .and Shop.sale.isNotNull .and (shop.discount.isNull() .or (shop.discount.isNotNull() .and shop.discount.approved.eq(SomeValue)))
    • 我们是否需要使用任何子查询,是否可以使用 MYSQL 和布尔表达式来实现这一点,对不起,如果我打扰了,我刚开始使用查询 DSL。
    • 也许可以在这里继续groups.google.com/forum/#!forum/querydsl
    猜你喜欢
    • 2018-04-30
    • 1970-01-01
    • 1970-01-01
    • 2015-02-26
    • 2014-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多