Hibernate one-to-many search with Criteria

亡梦爱人 提交于 2019-12-07 11:41:40

问题


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?


回答1:


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)));  

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



来源:https://stackoverflow.com/questions/3220873/hibernate-one-to-many-search-with-criteria

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!