3

I have a Spring Data & JPA QueryDSL based project in which I have many repository interfaces extending QueryDslPredicateExecutor like below:

public interface ProductRepository extends JpaRepository<Product, Long>,
    QueryDslPredicateExecutor<Product> {
}

I am performing findAll() queries with BooleanExpressions all over my application to fetch data. However I now need to find the distinct results of a query based on a particular column.

I am also using Projections & Custom repositories in some cases to select particular columns based on this post.

Is there a way to select distinct so that I only get the distinct values of a particular column for a query, based on any of the above approaches?

Community
  • 1
  • 1
ss_everywhere
  • 439
  • 7
  • 19

2 Answers2

4

Today I've encountered the same issue and it seems that there's no direct repository approach to solve it.

I ended using Querydsl in order to accomplish what I wanted: being able to use Page<T> findAll(Predicate var1, Pageable var2); using distinct.

A simple snippet:

public Page<LocalizedMessage> findAll(Predicate predicate, Pageable pageable) {
  QMessage qMessage = QMessage.message;

  Querydsl querydsl = new Querydsl(entityManager, new PathBuilder<>(Message.class, qMessage.getMetadata()));
  JPAQuery countQuery = querydsl.createQuery(qMessage).distinct().where(predicate);
  JPAQuery query = querydsl.createQuery(qMessage).distinct().where(predicate);
  querydsl.applyPagination(pageable, query);
  return PageableExecutionUtils.getPage(query.fetch(), pageable, countQuery::fetchCount);
}

This code is based on QuerydslJpaRepository's findAll(Predicate, Pageable) method. I presumed that it could be easy to extend this repository in order to add findAllDistinct methods using JPQLQuery.distinct().

I've filed a feature request at spring-data's JIRA.

Hope this helps someone.

Lasneyx
  • 2,110
  • 2
  • 17
  • 21
0

If you use Querydsl queries directly in your repository you can call query.distinct() to get distinct results.

Timo Westkämper
  • 21,824
  • 5
  • 78
  • 111