Given the following JPA annotated entity classes:
@Entity
@Table("foo")
public class Foo {
@Id private int id;
@Column(name="name") private String name;
@ManyToMany
@JoinTable(name = "foo_tags",
joinColumns = {@JoinColumn(name = "foo")},
inverseJoinColumns = {@JoinColumn(name = "tag")})
private Collection<Tag> tags;
...
}
@Entity
@Table(name = "tag")
public class Tag {
@Id private String tag;
...
}
I'm trying to formulate a query to get all Foo instances that lack a given tag. The following JPQL query does the trick
SELECT f FROM Foo f WHERE :tag NOT MEMBER OF f.tags
However, I'm having trouble translating this into a criteria query. The translation seems obvious (to me):
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Foo> query = cb.createQuery(Foo.class);
Root<Foo> from = query.from(Foo.class);
query.where(cb.isNotMember(cb.parameter(Tag.class, "tag"), from.get(Foo_.tags)));
TypedQuery<Foo> tq = em.createQuery(query);
return tq.setParameter("tag", sometag).getResultList();
The generated SQL differs significantly in these cases though. The first query generates the following:
SELECT t0.id, t0.name FROM foo t0
WHERE NOT EXISTS (
SELECT DISTINCT t2.TAG FROM tag t2, foo_tags t1
WHERE (((t1.foo = t0.id) AND (t2.TAG = t1.tag)) AND ('blue' = t2.TAG)))
while the criteria query generates this:
SELECT t1.id, t1.name FROM tag t0, foo_tags t2, Foo t1
WHERE (NOT ((t0.TAG = 'blue')) AND ((t2.foo = t1.id) AND (t0.TAG = t2.tag)))
I've only tested this using the eclipselink implementation, so possibly there's a problem there, but figured I'd ask here first if anyone spots an obvious mistake.