简体   繁体   中英

JPQL query for many to many relationship where item does not exist in join table

I'm trying to construct a JPQL query to select only VMs that do not exist in a Group. I have a many to many relationship between VMs and Groups:

class Group:

 @ManyToMany(fetch = FetchType.EAGER)
 @JoinTable(
     name="group_vm",
     joinColumns={@JoinColumn(name="group_id", referencedColumnName="id")},
     inverseJoinColumns={@JoinColumn(name="vm_id", referencedColumnName="id")}
 private Set<VM> vms;

This is fairly easy in SQL:

select * from vm where id not in (select vm_id from group_vm);

Is there a way to do this in JPQL?

Use NOT EXISTS

select vm from VM vm where not exists (select 1 from Group gr where vm member of gr.vms)

NOT IN should also work, but exists may be faster

select vm from VM vm where vm not in (select gr.vms from Group gr)

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