【发布时间】:2011-01-20 21:48:12
【问题描述】:
我有以下 POJO,里面有一个 Set:
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>
有两个表:word 和 word_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=?
也许我做错了什么?
【问题讨论】:
标签: java hibernate filter many-to-many