1

How to express a query with JPA 2.0 Criteria that should fetch all entities A that are not in relation (m:n) with an Entity B.

Domain Model:

@Entity class A{
  @Id int id;
  @ManyToMany List<B> disableForB;
}

@Entity class B{
  @Id int id;
}

The problem related to this domain model is: How to find all A that are not in relation disableForB for an specific B?

Ralph
  • 118,862
  • 56
  • 287
  • 383
  • see http://stackoverflow.com/questions/1578644/jpa-ql-how-to-not-select-something – David Holbrook Jul 10 '12 at 14:59
  • @David Holbrook: http://stackoverflow.com/questions/1578644/jpa-ql-how-to-not-select-something discuss this problem for JPQL but not for Criteria API – Ralph Jul 10 '12 at 16:44

1 Answers1

1

I do not have environment to test query available at the moment, so following can contain some mistake. This is anyway doable with isNotMember.

B b ...
CriteriaQuery<Aa> cq = cb.createQuery(A.class);
ParameterExpression<B> param = cb.parameter(B.class);
Root<A> a = cq.from(A.class);
Expression<Collection<B>> disabledB = a.get("disableForB");
Predicate pred = cb.isNotMember(param, disabledB);
cq.select(a);
cq.where(pred);
em.createQuery(cq).setParameter(param, b).getResultList();
Mikko Maunu
  • 41,366
  • 10
  • 132
  • 135