Skip to content
Advertisement

How to add parenthesis to queries in querydsl?

I’m using querydsl for sql selects. Now I have native query that I want to transform to querydsl. It consists of two OR statements in parenthesis, followed by and AND query that applies thereby to both OR parts.

I need the following:

((q1 AND q2) OR (q3 AND q4)) AND q5

In querydsl I can write for example:

BooleanExpression query = q1.and(q2).or(q3.and(q4)).and(q5)

But that’s not the same. What I really want is (note parenthesis):

BooleanExpression query = ((q1.and(q2)).or((q3.and(q4))).and(q5)

Question: how can I achieve this in java? How can I add those parenthesis logically to a querydsl expression.

Advertisement

Answer

Let’s assume we have three BooleanExpressions and we want to express (q1 || q2) && q3.

If you write q1.or(q2).and(q3), than the and statement is the top level operand and q1.or(q2) is first evaluated and then used as the left-side of the expression. This is due to the fact that the operations are evaluated in the order they appear. Remember, this is Java syntax. Hence, it would be valid to use the statement.

However, if you do not like the notation, an alternative would be to simply write the following:

q3.and(q1.or(q2)); 

See these examples for further information.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement