简体   繁体   中英

Do left outer join only if condition satisfies in JPA

I am new to JPA and trying to do a left outer join, only if a condition is satisfied in the native JPA query.

Native query is as shown below. Here I would like to do A left outer join B with the where condition, only if a given flag toJoin is true in application:

select a.id, a.name from A left outer join B on A.id = B.aid where b.name="some_name"

I am not sure, how will I accommodate the toJoin application flag in the above native JPA query in my JPA repository.

EDIT

I was just trying to achieve the same in mysql with the help of CASE WHEN and sample condition as follows:

select a.id from A a, case when 1=2 then left outer join B b ON a.id = b.aid end limit 2;

But I am getting syntaxt error.

Your question remains vague, however I suspect that your effort:

select a.id
from A a, case when 1=2 then left outer join B b on a.id = b.aid end
limit 2

Is meant to be:

select a.id, b.someColumn
from A a
left join B b on a.id = b.aid and 1=2
limit 2

Where 1=2 is actually some more complicated expression.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM