Hibernate one-to-many search with criteria

I have a Hibernate object called Event that has a one-to-many metadata object, 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 to create a Criteria request to retrieve an event that has BOTH tags "anotherTag" and "tagme"? In SQL, I would join the event_data table once for each tag found, but I can only create one alias for the Event.EventData relation, 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++; } 

Does not work; duplicate association path: Event.EventData

Similarly, the normal Conjunction does not work, because the sentence ends as:

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

and, unfortunately, the database field cannot have two different values ​​at the same time.

Any ideas on how I can clear this, or is this the only option coming back to HQL?

+4
source share
1 answer
 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 field size is ALWAYS the same, you can use Restrictions.eq ("fields", "tag") also * /

+4
source

Source: https://habr.com/ru/post/1315295/


All Articles