ddawg
ddawg

Reputation: 95

Hibernate criteria one-to-many distinct result

I have one person table. A person might have multiple kids, which are also persons. Thus, there is a one to many relationship between the person table.

I want to get all persons, which have at least one son (sex=male). I do this by following criteria:

List personsWithSon = sess.createCriteria(Person.class)
     .createAlias("kids", "k")
     .add( Restrictions.eq("k.sex", "male") )
     .list();

This is fine, as long as there is only one son. If there are e.g. three sons, the person is returned three times. But I just need the person one time. How can I do a distinct over the result?

Upvotes: 1

Views: 2047

Answers (1)

Atropo
Atropo

Reputation: 12531

Change it to:

List personsWithSon = sess.createCriteria(Person.class).createAlias("kids", "k").add(Restrictions.eq("k.sex", "male")).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();

Upvotes: 5

Related Questions