【问题标题】:Hibernate Criteria using collection (Set) in restrinction在限制中使用集合(集合)的休眠条件
【发布时间】:2018-03-01 05:46:13
【问题描述】:

我有一个像下面这样的 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;
}

我有一组人(所有者),比如组所有者。现在我想获取所有者的所有书籍(Set)。如何在 Hibernate 条件中添加此条件。我不想使用 HQL。

【问题讨论】:

    标签: java hibernate collections criteria hibernate-criteria


    【解决方案1】:

    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&lt;Book&gt;,但它也可以与Set&lt;Book&gt; 完美配合。

    请注意,.equals() 应在您的 Owner 类中正确实现,以获得正确的结果。

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

    【讨论】:

      【解决方案2】:

      我认为你需要像这样使用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))));
      

      【讨论】:

      • 兄弟,你从我嘴里说出来的话,实际上已经指出了;)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-17
      • 2013-03-20
      • 2011-03-26
      • 2011-02-25
      • 2011-12-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多