sinedsem
sinedsem

Reputation: 5723

How to get unique results from joined Hibernate queries

This is a continuation to questions like this: why does hibernate hql distinct cause an sql distinct on left join?

You may have noticed that findAll() repository methods return duplicates, while findAll(Pageble pageble) works fine.

So, I would like to share additional way to obtain unique results.

Upvotes: 0

Views: 293

Answers (1)

sinedsem
sinedsem

Reputation: 5723

So, let's have a look at org.hibernate.hql.internal.ast.QueryTranslatorImpl

final boolean hasLimit = queryParameters.getRowSelection() != null && queryParameters.getRowSelection().definesLimits();
final boolean needsDistincting = ( query.getSelectClause().isDistinct() || hasLimit ) && containsCollectionFetches();

As you can see, Hibernate will apply distincting if you define limits. That is, if you are afraid of the word distinct in your queries and criteria, just call javax.persistence.Query.setFirstResult(0); and this will make Hibernate apply distincting.

Upvotes: 1

Related Questions