mengmeng
mengmeng

Reputation: 1486

Sort by column using Specification in Spring

I have a dilemma on how to sort a column by the count of an entity from another table.

I have two entities

@Entity 
public class Plan {

   Long id;
   String name;
   PlanStatus status;
   LocalDateTime dateCreated;
   LocalDateTime lastUpdated;
}
@Entity 
public class Subscription {
   Long id;
   Plan plan;

Right now, I just directly passed the Sort sort for the repository implemented with Pagable (pageRequest) return smsPlanRepository.findAll(planSpecification, pageRequest);

But is there a way where I could use Specification with the number of Subcriber of each Plan?

public Specification<Plan> hasSort(String sortBy) {
    return (root, query, criteriaBuilder) -> {
    
        return //count of by Plan in Subscribers
    }
}

Thank you for your help in advance!

Upvotes: 3

Views: 530

Answers (1)

Alex Ciocan
Alex Ciocan

Reputation: 2322

Besides pageable interface, spring specifications can also make use of sorting via the criteriaBuilder api as bellow:

public Specification<Plan> hasSort(String sortBy) {
    return (root, query, criteriaBuilder) -> {
    
    query.multiselect(root.get("fields..."),
                criteriaBuilder.count(root.get("count_field")));

    query.orderBy(criteriaBuilder.desc(criteriaBuilder.count(root.get("count_field")));
    
     return //count of by Plan in Subscribers
    }
}

Upvotes: 1

Related Questions