JPA Criteria Set/List not usable as PluralAttribute to make a Predicate

3k views Asked by At

I have an entity class X which has a collection of Y entities.

X

@ManyToMany
private List<Y> items = new ArrayList<>();

I'm trying to make a JPA criteria query restriction to test if an instance of Y exists in the collection.

X entity = ...; // Some instance
Predicate p = criteriaBuilder.isMember(entity, subRoot.get(X_.items))

Gives me an error of: (argument mismatch; ListAttribute<X,Y> cannot be converted to PluralAttribute<X,C,E>))

When I look at the metamodel the List attribute is like this:

public static volatile ListAttribute<X, Y> items;

Going to the ListAttribute definition:

public interface ListAttribute<X extends Object, E extends Object> 
    extends PluralAttribute<X, List<E>, E> {

I've tried casting the criteriaBuilder.isMember(entity, (PluralAttribute)subRoot.get(X_.items)) and changing from a Set to a List.

Should this be possible or is there an alternative way to check if an object occurs in a collection in a JPA Criteria query?

1

There are 1 answers

0
lko On BEST ANSWER

We got it working with a join.

Join join = root.join(root.get(X_.items);

query.where(criteriaBuilder.equal(root.get(X_.items), entity))

The output was something like this:

select x_.* from X x inner join X_Item item_ on x_.id=item_.X_id where x_.item_id=?