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) ?
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)")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With