gpt4 book ai didi

java - Hibernate多对多集合过滤

转载 作者:搜寻专家 更新时间:2023-11-01 03:14:37 25 4
gpt4 key购买 nike

我有以下带有 Set 的 POJO:

class Word {
private Long id;
private String word;
private int type = WordListFactory.TYPE_DEFAULT;

private Set<Word> refs = new HashSet<Word>();
...
}

这是映射 XML:

  <class name="kw.word.Word" table="word">
<id name="id" column="id" unsaved-value="null">
<generator class="native"/>
</id>

<property name="word"
unique="true"
not-null="true"/>
<property name="type"/>

<set name="refs"
table="word_key"
cascade="save-update">

<key column="word_id"/>
<many-to-many class="kw.word.Word"
column="word_ref_id"
fetch="join">
</many-to-many>
</set>


</class>

有两个表:wordword_key。后者将 word-parents 链接到 word-children。

当从数据库中获取数据时,我正在尝试实现设置项过滤。生成的对象集必须仅包含特定类型的项目。

我尝试了很多事情:

  • 像这样在映射中使用过滤(抱歉缺少括号)
    
many-to-many class="kw.word.Word"
column="word_ref_id"
fetch="join">
filter name="word_type" condition="type=:type"
many-to-many

在获取数据的代码中,我启用了过滤器并设置了参数。根据日志,hibernate 似乎忽略了这个特定的过滤器,因为它在生成的 SQL 查询中没有条件。

  • 在条件中使用附加条件

      Word result = null;

    session.beginTransaction();

    Criteria crit = session.createCriteria(Word.class);

    crit.add(Restrictions.like("word", key))
    .createAlias("refs", "r")
    .add(Restrictions.eq("r.type", getType()));//added alias and restriction for type

    List list = crit.list();

    if(!list.isEmpty())
    result = list.get(0);

    session.getTransaction().commit();

现在生成的 SQL 似乎没问题了

   select
this_.id as id0_1_,
this_.word as word0_1_,
this_.type as type0_1_,
refs3_.word_id as word1_,
r1_.id as word2_,
r1_.id as id0_0_,
r1_.word as word0_0_,
r1_.type as type0_0_
from
word this_
inner join
word_key refs3_
on this_.id=refs3_.word_id
inner join
word r1_
on refs3_.word_ref_id=r1_.id
where
this_.word like ?
and r1_.type=?

但是在这个查询之后还有另一个获取所有项目的查询

 select
refs0_.word_id as word1_1_,
refs0_.word_ref_id as word2_1_,
word1_.id as id0_0_,
word1_.word as word0_0_,
word1_.type as type0_0_
from
word_key refs0_
left outer join
word word1_
on refs0_.word_ref_id=word1_.id
where
refs0_.word_id=?

也许我做错了什么?

最佳答案

从你给定的代码片段几点:

  • 如果是多对多关系,您需要 3 个表、两个实体表和一个连接表。但是由于您拥有相同的实体 -Word,我认为给定的表结构和映射似乎没问题。
  • 尝试使用 HQL 并指定“LEFT JOIN FETCH”以指定您需要在初始 sql SELECT 中检索哪些关联。

看到这个链接涉及多对多关系,但是他们使用了条件查询。

Querying ManyToMany relationship with Hibernate Criteria

关于java - Hibernate多对多集合过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2332487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com