Hibernate: query objects that contain a specific element in CollectionOfElements?

Let's say I have this object (for Hibernate):

@Entity
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    Long id;

    @CollectionOfElements
    @IndexColumn("phones_index")
    Set<String> phones;
}

For example, I want to get instances of Person where their phones contain "555-1234". How can I make a request on this? I am looking for something similar to:

session.createCriteria(Person.class)./*something*/.add(Restrictions./*something*/"555-1234").list();
+5
source share
2 answers

Hi you can try this

String phone = "555-1234";
Person person= (Person) session.createQuery("from Person p join p.phones pl where pl = :phone").setString("phone", phone).uniqueResult();
+9
source

I think you need a Hibernate method Restrictions.in()that takes a property name as the first argument and either an array or a collection of objects as the second.

See also: Javadoc

: , , Restrictions, , eq:

session.createCriteria(Person.class).add(Restrictions.eq("phones", "555-1234")).list();
-1

All Articles