I came across the same issue, so in case it would help someone, this is what I did:
The Specification is being translated to the where clause, and the findAll(Specification<T>)
function is creating its own select clause. So there is no way we can fix this by somehow using the findAll(Specification<T>)
function.
I already had custom repository which extends SimpleJpaRepository
, so I've added a new method:
@Override
@Transactional(readOnly = true)
public List<Object> findDistinctValues(Specifications<T> spec, String columnName) {
return getQuery(spec, columnName).getResultList();
}
protected TypedQuery<Object> getQuery(Specification<T> spec, final String distinctColumnName) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Object> query = builder.createQuery(Object.class);
Root<T> root = applySpecificationToCriteria(spec, query);
if (null != distinctColumnName) {
query.distinct(true);
query.multiselect(root.get(distinctColumnName));
}
// We order by the distinct column, Asc
query.orderBy(builder.asc(root.get(distinctColumnName)));
return em.createQuery(query);
}
applySpecificationToCriteria
is in the SimpleJpaRepository
class.
Now you can use the findDistinctValues
method.