Queries with a join fetch can return duplicate results
for example :
I have classes A and B
A has a collection of B
The following query would return a A having 3 B in his collection
"from A a join fetch B where a.id = 1"
The resulting list contains 3 elements, all the same instance of A. Duplicates can be eliminated by putting the list into a HashSet, as suggested in this article :
http://www.hibernate.org/117.html#A11
And this works fine, because HashSets don't allow doplicates, and only 1 will be stored in the HashSet.
The real problem is when the query is on more than one entity.
For example :
I have classes A, B, X
A has a collection of B
The following query would return a A having 3 B in his collection, and only 1 X associated to this A :
"from A a, X x join fetch B where a.something = x.something and a.id = 1"
So the resulting list contains 3 elements of the type Object[2], each of these elements containing a A and a X. It is the same instance of A and X in all these 3 elements.
The suggested solution from the article doesnt work here. Putting it in a HashSet won't eliminate duplicates. A HashSet doesn't allow duplicates to be added, but it detect a duplicate by calling .equals() on the objects. But for a array like our Object[2], calling .equals() doesn't really compare the contents, the real way to compare arrays is with Arrays.equals(array1, array2).
Did anyone face this problem before? And if so, how did you solve it?