假设我有两个 JPA 实体:
@Entity
public class EntityA {
@Id
private String id;
@OneToMany
private List<EntityB> b;
...
}
@Entity
public class EntityB {
@Id
private String id;
...
}
我想要完成的是定义一个@NamedQuery
检索所有EntityB
未从任何EntityA
.
天真地,我会尝试的
@NamedQuery(name = "EntityB.findAllUnassigned", query = "SELECT b FROM EntityB b WHERE NOT b IN (SELECT DISTINCT a.b FROM EntityA a)")
但这最终会生成无效的 SQL:
select b0_.id as id1_, b0_.attr, ... from b b0_ where b0_.id not in (select distinct . from a a1_, a_b ab2_, b b3_ where a1_.id=ab2_.a_id and ab2_.b_id=b3_.id)
有什么选择吗?