Reputation: 439
I have a problem with Sorting in Spring. I have an enum class
public enum Category {
A,
B,
C,
D,
E,
F;
private static final List<Category> THRILLER;
static {
THRILLER = Arrays.asList(A, F, D);
}
private static final List<Category> DRAMA;
static {
DRAMA = Arrays.asList(C, E, B);
}
}
The Movie Entity:
@Entity
@Table
public class Movie {
...
private Category category;
private Timestamp realizationDate;
....
}
Now I have a rest endpoint that return movies List. I want to Sort this list according to the following order: Movies they belong to THRILLER should be displayed first. When two movies belong to the same category then this should be sorted by realization date.
@GetMapping(value = "/movies")
public ResponseEntity<PagedResources<Movie>> list(@PageableDefault() Pageable pageable) {
.......
}
I tried it with:
@SortDefault.SortDefaults({SortDefault(sort="category", direction=Sort.Direction.ASC), SortDefault(sort="realizationDate", direction=Sort.Direction.ASC)})
But this Sort the enum only alphabetically.
I need a possibility to do something like: Sort.by(Category.THRILLER.contains(movie.getCategory()))
. It is possible that I achieve that with Pageable or should I do it another way?
Upvotes: 1
Views: 2523
Reputation: 81988
Spring Data directly only supports sorting by simple attributes.
So in order for this to work you need to provide an isThriller
attribute.
You can do this with the existing object structure by using:
a) a trigger to fill the column in the database
b) use a view to compute the desired value
c) if you use Hibernate you may use the @Formula
annotation to instruct it to compute the value.
In either case you are hardcoding the categories that make up thrillers in a String or in the database.
If you don't want that you could make Category
an entity with an isThriller
attribute which you then can query and sort by in the usual fashion.
Upvotes: 4
Reputation: 2376
AFAIK Sort
in spring pagination sorts fields only in lexicographical order (same like in SQL, uneless you use some procedural version of SQL like PSQL) so you can't introduce some custom logic of sort.
You have two options:
Upvotes: 1