tags:

views:

474

answers:

3

Is anyone aware of the validity of Hibernate's Criteria.list() and Query.list() methods returning multiple occurrences of the same entity?

Occasionally I find when using the Criteria API, that changing the default fetch strategy in my class mapping definition (from "select" to "join") can sometimes affect how many references to the same entity can appear in the resulting output of list(), and I'm unsure whether to treat this as a bug or not. The javadoc does not define it, it simply says "The list of matched query results." (thanks guys).

If this is expected and normal behaviour, then I can de-dup the list myself, that's not a problem, but if it's a bug, then I would prefer to avoid it, rather than de-dup the results and try to ignore it.

Anyone got any experience of this?

+5  A: 

Yes, getting duplicates is perfectly possible if you construct your queries so that this can happen. See for example Hibernate CollectionOfElements EAGER fetch duplicates elements

Eemeli Kantola
+1. How can I not upvote someone linking to my answer? :-) Seriously, however - yes, Hibernate may return duplicates when more than one "to-many" association is either declared with eager fetch or retrieved using join fetch within the same query. Look at the note at the bottom of 14.3: http://docs.jboss.org/hibernate/stable/core/reference/en/html/queryhql.html#queryhql-joins
ChssPly76
Thanks for the doc link, I knew it had to be in there somewhere
skaffman
+2  A: 

If you have an object which has a list of sub objects on it, and your criteria joins the two tables together, you could potentially get duplicates of the main object.

One way to ensure that you don't get duplicates is to use a DistinctRootEntityResultTransformer. The main drawback to this is if you are using result set buffering/row counting. The two don't work together.

_Mike
A: 

I get duplicate rows when I use only simple class like:

return session.createCriteria(Lfatypy.class).list();

James