简体   繁体   中英

JPA Query join with where clause on join table

I would like to write a query that retrieves the following:

  • Clients containing no contacts
  • Clients containing contacts, but only the contact entities with status 'AC'

    SELECT client from Client client LEFT JOIN FETCH client.contacts contact WHERE (client.contacts IS EMPTY OR (client.contacts IS NOT EMPTY AND contact.status = 'AC'))

This query only returns my clients without contacts or clients which has only active contacts. Can someone help me out?

I'm using JPA1. I'm not able to switch to JPA2. It also needs to be a JPA1 query.

When I've the following data in my db:

  • Client 1 --> contacts: contact 1 with status AC, contact 2 with status AR
  • Client 2 --> contacts: contact 3 with status AR, contact 4 with status AR
  • Client 3 --> contacts: contact 5 with status AC, contact 6 with status AC

I would like to retrieve

  • Client 1 with only contact 1
  • Client 2 without any contacts
  • Client 3 with contact 5 and 6

"WHERE client.status = 'AC' AND" means you only get clients with status AC. Do you mean "WHERE contact = null OR contact.status = 'AC'"?

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