【问题标题】:Hibernate select manyToMany association with a criteria containing all the elements of a listHibernate select manyToMany 与包含列表所有元素的条件关联
【发布时间】:2013-01-09 09:46:58
【问题描述】:

我有两个休眠实体 A 和 B。 A 和 B 之间存在 ManyToMany 关联。

public class A {
  @ManyToMany(targetEntity=B.class)
  @JoinTable(name = "AB",
    joinColumns = @JoinColumn(name="A_FK"),
    inverseJoinColumns = @JoinColumn(name="B_FK"))  
  private Set<B> collectionOfB = new HashSet<B>();
  // ...
}

public class B {
  // no reference to A
}

我有一个由 B 个元素组成的数组 {b1, b2,... ,bn}。

我需要搜索与上面列表中所有 B 元素相关联的所有 A 元素({b1, b2,... ,bn} 的所有元素都应该在 collectionOfB 中)。

所以我必须这样做:

select * from A as a where {b1, b2,... ,bn} in a.collectionOfB 

但这是不可能的:-(

有人知道如何处理这个问题吗?

谢谢

卡姆兰

【问题讨论】:

    标签: hibernate many-to-many hql hibernate-criteria


    【解决方案1】:

    如果您的映射正确,您可以这样做:

        sql="select a.* from A a where ...";
        for (Long bId: myListOfBcriteria) {
            sql += " and " + bId+ " in (select ab.b_fk from AB ab where ab.a_fk=a.id)";
        }
    

    处于休眠状态。

        select a from A join a.collectionOfB as ab where ab.id in (:collectionOfB)
    

    如果你打算使用 ORM,你应该使用它,除非你绝对不能。

    【讨论】:

    • 尊敬的 Carbontax,谢谢您的回答。不,我需要我的查询集合的所有元素都在 a.collectionOfB 中(或者你写的 a.b 中)
    【解决方案2】:

    经过一番调查,我发现解决我的问题的最简单方法是通过session.createSQLQuery(sql) 使用本机 SQL。

    与:

    sql="select a.* from A a where ...";
    for (Long bId: myListOfBcriteria) {
      sql += " and " + bId+ " in (select ab.b_fk from AB ab where ab.a_fk=a.id)";
    }
    

    myListOfBcriteria={b1, b2,... ,bn}.

    也许它不是很“好”,但效果很好:-)

    希望对大家有所帮助

    卡姆兰

    【讨论】:

    • 我编辑了我的答案以反映您的新内容。也许您也应该编辑您的问题。这是 Stackoverflow 的做事方式。
    猜你喜欢
    • 2022-10-23
    • 1970-01-01
    • 2015-05-14
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    • 2018-09-11
    • 1970-01-01
    • 2020-09-29
    相关资源
    最近更新 更多