Hibernate: Query entities which contain a specified element in a CollectionOfElements?

Let's say I have this entity (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 do a query on this? I am looking for something similar to:

session.createCriteria(Person.class)./*something*/.add(Restrictions./*something*/"555-1234").list();

Upvotes: 5

Views: 3889

Answers (2)

imambenjol
imambenjol

Reputation: 196

Hi you can try this one

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

Upvotes: 9

Adam Batkin
Adam Batkin

Reputation: 53034

I think you want Hibernate's Restrictions.in() method, which takes a property name as the first argument, and either an array or Collection of objects as the second.

See also: The Javadoc

Edit: Upon re-reading your question, I think you can use any of the relevant Restrictions methods, in particular, eq:

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

Upvotes: -1

Related Questions