Hibernate 使用 Criteria 进行一对多搜索
我有一个名为 Event 的 Hibernate 实体,它有一个一对多元数据实体 EventData。
给定以下事件:
EventId:1
EventHash:西兰花
具有以下事件数据:
EventDataId:1
事件ID:1
字段:标签
内容:tagme
EventDataId:2
事件ID:1
字段:标签
内容:anotherTag
如何创建条件查询来检索同时具有“anotherTag”和“tagme”标签的事件?在 SQL 中,我会为每个正在搜索的标签加入一次 event_data 表,但我似乎只能为 Event.EventData 关系创建一个别名,即
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
类似地,普通的连接不起作用,因为该子句最终为:
((ed3_.field='tag' and ed3_.content='anotherTag') and (ed3_.field='tag' and ed3_.content='tagme'))
并且遗憾的是,数据库字段不能同时具有两个不同的值。
关于如何清理这个问题的任何想法,或者是恢复到 HQL 的唯一选择?
I've got a Hibernate entity, called Event, which has a one-to-many metadata entity, EventData.
Given the following Event:
EventId: 1
EventHash: broccoli
With the following EventDatas:
EventDataId: 1
EventId:1
Field: tag
Content: tagme
EventDataId: 2
EventId: 1
Field: tag
Content: anotherTag
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++;
}
Doesn't work; duplicate association path: Event.EventData
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.
Any ideas as to how I could clean this up, or is the only option reverting to HQL?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
/* 如果字段的大小始终为 1,则也可以使用 Restrictions.eq("fields", "tag") */
/* if the size of fields is ALWAYS one, you can use Restrictions.eq("fields", "tag") also*/