ss_everywhere
ss_everywhere

Reputation: 479

Spring Data JPA QueryDslPredicateExecutor find distinct results

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?

Upvotes: 3

Views: 4181

Answers (2)

Lasneyx
Lasneyx

Reputation: 2310

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.

Upvotes: 4

Timo Westk&#228;mper
Timo Westk&#228;mper

Reputation: 22180

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

Upvotes: 0

Related Questions