Is it valid for Hibernate list() to return duplicates?

Viewed 21103

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?

4 Answers

I had the exact same issue with Criteria API. The simple solution for me was to set distinct to true on the query like

CriteriaQuery<Foo> query = criteriaBuilder.createQuery(Foo.class);
query.distinct(true);

Another possible option that came to my mind before would be to simply pass the resulting list to a Set which will also by definition have just an object's single instance.

Related