Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate JOIN FETCH when no relation exists

I have a Customer entity with @OneToMany Account children. I want perform fetch join to return a customer with its corresponding active accounts (having account.isActive = true). If the customer does not have any accounts it needs to be returned as well.

For the following JPQL, for a customer having inactive accounts, they are indeed filtered out, but a customer without any accounts is not returned:

   @NamedQuery(name = "Customer.findById", query = "SELECT c FROM Customer c LEFT JOIN FETCH c.accounts a WHERE c.id = :id AND a.isActive=true")

What would be the clean way to write the query so that both cases would be covered (customer with no accounts and customer with active accounts) ?

like image 915
ReggieK123 Avatar asked Dec 05 '25 05:12

ReggieK123


1 Answers

So, basically, answering my own question - the solution was pretty easy:

 @NamedQuery(name = "Customer.findById", query = "SELECT c FROM Customer c LEFT JOIN FETCH c.accounts a WHERE c.id = :id AND (a is null OR a.isActive=true)")
like image 84
ReggieK123 Avatar answered Dec 07 '25 03:12

ReggieK123



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!