views:

55

answers:

1

Hi all,

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?

+2  A: 
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*/

becomputer06
Superb, thank you!
Martin