Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QueryDSL AND/ OR Operator Not Working with BooleanExpression

Tags:

querydsl

We are Doing a search on an entity , we are using Query DSL .

the table structure is as follows

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

We need to build a predicate which returns all the shops which does not have discounted
Sale and also that has discounted Sale .

We are Using MySQL Database and JPA as our persistence framework .

Scenario is that we are performing a search and search should get out all the shops with no discounts and shops with discounts approved.

the below are our boolean expressions that we have it at present.

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)

now we need to build query to get all the shops which don't have a discount , and also all the shops which have a discount and Approved .

we tried with the predicate

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

We expect the query to be

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'))

but what the query generated is

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`')

we are not getting out the proper resultset with this predicate ,

Is there any Way I can rewrite the predicate to make it working as expected ? kindly help me with suggestions.

thanks Saravana.

like image 531
saravanau Avatar asked Nov 10 '22 08:11

saravanau


1 Answers

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

is equivalent to

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

See here for MySQL operator precedence https://dev.mysql.com/doc/refman/5.0/en/operator-precedence.html

Concerning your example this should work

shop.discount.isNull()
.or(shop.discount.isNotNull()
    .and(shop.discount.approved.eq(SomeValue)))
like image 88
Timo Westkämper Avatar answered Jan 04 '23 02:01

Timo Westkämper