问题
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.
回答1:
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
}
}
来源:https://stackoverflow.com/questions/42652129/spring-data-rest-projection-sorting