Search code examples
javahibernatecollectionscriteriahibernate-criteria

Hibernate Criteria using collection (Set) in restrinction


I have a Pojo class like below.

public class Book{

  @Id
  @Column(name = "ID", unique = true, nullable = false)
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  long id;

  @Column(name = "NAME", nullable = false)
  String name;

  @OneToOne
  @JoinColumn(name = "PERSON_ID", nullable = false)
  Person owner;
}

I have Set of persons(owner) like Set owners. Now I want to fetch all the books of owners (Set). How can I add this condition in Hibernate criteria. I don't want to use HQL.


Solution

  • I think you need to use Restrictions.in like so :

    Criteria criteria = session.createCriteria(Book.class)
                        .add(Restrictions.in("owner", 
                                   new Person[] {person1, person2, person1}));
    
    List<Book> resultList = criteria.list();
    

    Also I think it is possible to use :

    Criteria criteria = session.createCriteria(Book.class)
                            .add(Restrictions.in("owner", 
                                    new HashSet<>(Arrays.asList(person1, person2, person1))));