使用Criteria进行一对多的Hibernate搜索 [英] Hibernate one-to-many search with Criteria

查看:128
本文介绍了使用Criteria进行一对多的Hibernate搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为Event的Hibernate实体,它有一对多元数据实体EventData。

I've got a Hibernate entity, called Event, which has a one-to-many metadata entity, EventData.

给定以下事件:

EventId:1

EventHash:broccoli

EventId: 1
EventHash: broccoli

使用以下EventDatas:

With the following EventDatas:

EventDataId:1

EventId:1

字段:tag

内容:tagme

EventDataId: 1
EventId:1
Field: tag
Content: tagme

EventDataId:2

EventId:1

字段:tag

内容:anotherTag

EventDataId: 2
EventId: 1
Field: tag
Content: anotherTag

如何创建Criteria查询以检索具有BOTH标签anotherTag和tagme的事件?在SQL中,我为每个被搜索的标签加入event_data表一次,但我似乎只能为Event.EventData关系创建一个别名,即

How do I create a Criteria query to retrieve the event which has BOTH tags "anotherTag" and "tagme"? In SQL, I'd join the event_data table once for each tag being searched for, but I can only seem to create one alias for the Event.EventData relationship, i.e.

int inc = 0;

Conjunction junc = Restrictions.conjunction();

for ( String tag : tags ) {
    crit.createAlias("e.EventData", "ed"+inc);
    junc.add(
        Restrictions.and(
            Restrictions.eq("ed"+inc+".field", "tag"),
            Restrictions.eq("ed"+inc+".content", tag)
        )
    );
    inc++;
}

不起作用; 重复的关联路径:Event.EventData

同样,正常的连接不起作用,因为该子句最终as:

Similarly, a normal Conjunction doesn't work, because the clause ends up as:

((ed3_.field='tag' and ed3_.content='anotherTag') and (ed3_.field='tag' and ed3_.content='tagme'))

,遗憾的是,数据库字段可以同时有两个不同的值。

and, sadly, the database field can't have two different values at the same time.

关于如何清理它的任何想法,或者是恢复到HQL的唯一选择?

Any ideas as to how I could clean this up, or is the only option reverting to HQL?

推荐答案

List fields = new ArrayList(1);
fields.add("tag")

List contents = new ArrayList(tags.size());
for ( String tag : tags ) {
    contents.add(tag);
}

session.createCriteria(Event.class);
criteria.createCriteria("eventDatas").add(Restrictions.and(Restrictions.in("field", fields), Restrictions.in("content", contents)));  

/ *如果字段大小总是一个,你可以使用Restrictions.eq(fields ,tag)* /

/* if the size of fields is ALWAYS one, you can use Restrictions.eq("fields", "tag") also*/

这篇关于使用Criteria进行一对多的Hibernate搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆