wiki:Jpa2QueryElementCollection

JPA2 introduces some excellent features, such as as the @ElementCollection annotation (like the CollectionOfElements annotation from Hibernate). However, when trying to use this feature with Hibernate 3.5.0-Beta-3 I had some trouble querying by the collection element. Some sites  1  2 suggested something like SELECT b FROM Book b WHERE b.tags = ’scifi’. However, with the Hibernate implementation at least, this does not work (note that 2 uses Glassfish and 1 uses Eclipselink), rather I get Caused by: org.hibernate.TypeMismatchException: left and right hand sides of a binary logic operator were incompatible [java.util.Collection(Object1.middleNames) : string]. The solution seems to be to create an INNER JOIN and compare to the joined table/object.

@Entity
@Table(name="OBJECTS")
public class Object1 {
        @Id
        @GeneratedValue(strategy=GenerationType.AUTO)
        private long id;
        @Basic
        private String name;
        @ElementCollection
        @CollectionTable(name ="middleNames")
        private List<String> middleNames = new ArrayList<String>();
...
Query q = em.createQuery("FROM Object1 o JOIN o.middleNames n WHERE n='Donald'");