Hibernate Criteria 在限制条件下使用集合(Set)

Hibernate Criteria using collection (Set) in restrinction

我有一个 Pojo class 如下所示。

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;
}

我有 Set of persons(owner) 喜欢 Set owners。现在我想获取所有者(Set)的所有书籍。如何在 Hibernate 条件中添加此条件。我不想使用 HQL。

我认为你需要像这样使用 Restrictions.in :

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

List<Book> resultList = criteria.list();

另外我认为可以使用:

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

好的 Criteria 你可以使用 Restrictions.in() 这样的方法:

List<Book> books = session.createCriteria(Book.class)
    .createAlias("owner", "o")
    .add(Restrictions.in("o", ownersCollection.toArray(new Book[ownersCollection.size()])))
    .list();

其中 ownersCollection 是您的所有者集合,在此代码中我将 ownersCollection 用作 List<Book>,但它也可以与 Set<Book> 完美配合。

请注意,.equals() 应该在您的 Owner class 中正确实施才能获得正确的结果。

如需进一步阅读,您可以查看: