我有以下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 。后者将文字父母与文字儿童联系起来。
我正在尝试从数据库中提取数据时实现设置项过滤。生成的对象集必须仅包含具有特定类型的项目。
我尝试了各种各样的事情:
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=?
也许我做错了什么?
答案 0 :(得分:3)
从您给定的代码段中得出几点:
请参阅此链接与多对多关系相关,但他们使用了条件查询。