I am using Criteria Api to sort and filter my data. The sort functionallity looks like this:
Expression<Object> caseExpression = criteriaBuilder.selectCase()
.when(criteriaBuilder.equal(root.get("status"), Status.ERROR), 1)
.when(criteriaBuilder.equal(root.get("status"), Status.WARNING), 2)
.when(criteriaBuilder.equal(root.get("status"), Status.OK), 3)
.otherwise(4);
Order order=criterBuilder.asc(caseExpression).
CriteriaQuery.orderBy(order);
Now the code works and the list is sorted accordingly to the cases but if there are multiple objects in the same case, they don't get sorted and the order of the elements is different everytime.
Output Example: 1.
Id | Status | Updated |
---|---|---|
24 | ERROR | 11.04.2024, 09:13 |
28 | ERROR | 11.04.2024, 09:15 |
30 | ERROR | 11.04.2024, 09:20 |
16 | WARNING | 11.04.2024, 08:20 |
2. | Id | Status | Updated | | -------- | -------- | ----------------- | | 28 | ERROR | 11.04.2024, 09:15 | | 30 | ERROR | 11.04.2024, 09:20 | | 24 | ERROR | 11.04.2024, 09:13 | | 16 | WARNING | 11.04.2024, 08:20 |
This is because there is no order in the cases, now comes the question: How can I sort the objects in the same case so that they don't show in a random order?
Help and Tips are appreciated.
Tried: I can't put the criteriaBuilder.asc into the case Predicates because it is an order. The orderBy just sorts the cases. OrderBy with order list also doesn't work.
You could add one more sort condition after status
:
Expression<Object> caseExpression = criteriaBuilder.selectCase()
.when(criteriaBuilder.equal(root.get("status"), Status.ERROR), 1)
.when(criteriaBuilder.equal(root.get("status"), Status.WARNING), 2)
.when(criteriaBuilder.equal(root.get("status"), Status.OK), 3)
.otherwise(4);
Order orderStatus = criteriaBuilder.asc(caseExpression);
Order orderUpdated = criteriaBuilder.asc(root.get("Updated"));
criteriaQuery.orderBy(orderStatus, orderUpdated);
This means: sorting by the Updated
field when the Status
is the same.