Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data Rest projection sorting

I have a projection for my entity and I need to sort it by field of inner class. This is part of my entities:

class Person {
    UUID guid;
    Set<DisabilityHistory> disabilityHistory;
}
class DisabilityHistory {
    Date createdDate;
}

I know about sort param but request like api/person/search?projection=myProjection&sort=disabilityHistory.createdDate,asc doesn't work. The only solution I have found is using @OrderBy annotation in my entity but in this case it will sorted always and I worried about performance.

like image 965
Kadzhaev Marat Avatar asked Sep 18 '25 10:09

Kadzhaev Marat


1 Answers

This will not work as you are trying to sort an inner field in your entity, so you can't do it on DB level. The way I've used it is by sorting it in the Projection class using SpEL. This is an example of how you can do it:

@Projection(
        name = "sorted",
        types = Person.class
)
public interface PersonProjection {

    @Value("#{@personProjectionHelper.sortedByDisabilityHistory(target.disabilityHistory)}")
    List<DisabilityHistory> getDisabilityHistory();
}

And implement the sorting in Java:

@Component
public class PersonProjectionHelper {

    public List<DisabilityHistory> sortByDisabilityHistory(final List<DisabilityHistory> list) {
        // do the sorting on Java level
    }
}
like image 118
Yuriy Yunikov Avatar answered Sep 21 '25 00:09

Yuriy Yunikov