简体   繁体   English

在回收中使用集合(集合)的休眠条件

[英]Hibernate Criteria using collection (Set) in restrinction

I have a Pojo class like below. 我有一个如下的Pojo课堂。

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. 我有一组人(所有者),如Set所有者。 Now I want to fetch all the books of owners (Set). 现在,我想获取所有所有者的书籍(Set)。 How can I add this condition in Hibernate criteria. 如何在休眠条件中添加此条件。 I don't want to use HQL. 我不想使用HQL。

I think you need to use Restrictions.in like so : 我认为您需要像这样使用Restrictions.in

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

Well with Criteria you can use Restrictions.in() method like this: 有了Criteria您可以使用Restrictions.in()方法,如下所示:

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

Where ownersCollection is your collection of owners, in this code I used ownersCollection as a List<Book> but it will also work perfectly with Set<Book> . ownersCollection是您的所有者集合,在此代码中,我使用ownersCollection作为List<Book>但它也可以与Set<Book>完美配合。

Note that .equals() should be correctly implemented in your Owner class in order to get correct results. 请注意,应在Owner类中正确实现.equals()以获得正确的结果。

For further reading about it you can check: 要进一步了解它,您可以检查:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM