How to query a property of type List<String>in JPA

Guido picture Guido · Dec 29, 2009 · Viewed 43.2k times · Source

Lets say we have this JPA-annotated class, with a property of type List. This code is currently working fine.

@Entity
public class Family {
    ...
    @CollectionOfElements(targetElement=java.lang.String.class)
    @JoinTable(name = "elements_family",
        joinColumns = @JoinColumn(name = "idFamily")
    )
    @Column(name = "element", nullable = false)
    private List<String> elements;
    ...
}

Is there any way to query for the list of Families that contain the element "yyy" ? That is, something like:

Query query = getEntityManager().createQuery("select f FROM Family f WHERE element = :element");
query.setParameter("element", "yyy");
return query.getResultList();

Answer

axtavt picture axtavt · Dec 29, 2009

MEMBER OF clause in JPQL:

Query query = getEntityManager().createQuery("select f FROM Family f WHERE :element MEMBER OF f.element"); 
query.setParameter("element", "yyy"); 
return query.getResultList();