I currently have a system in place which can filter and sort records in the database and return them as a Paged object. One of the lines is like this:
final
I think you could try the Spring Data JpaSort
class which allows function calls.
As stated in the documentation you will have something like :
@Query("select u from User u where u.lastname like ?1%")
List<User> findByAndSort(String lastname, Sort sort);
repo.findByAndSort("targaryen", JpaSort.unsafe("LENGTH(firstname)"));
You could also use it with a Pageable object.
Assume that you have entity with a String
filed and you want to sort it like Long
with jpa Pageable.
So you need to do following things:(Remember this only works with Oracle Database)
Long
type@Formula
in getter method and evoke to_number()
@Entity public class testEntity{ private String oldField; //Getter and Setter private Long newField; //Setter @Formula(value = "to_number(oldField)") public Long getNewField() { return newField; } }
newfiled
if (Objects.nonNull(pagingRequest.getSort()) && pagingRequest.getSort().getFieldName().equals("oldField")) { pagingRequest.getSort().setFieldName("newField"); }
So basically you need to do two things:
public class HouseComparator implements Comparator<House> {
@Override
public int compare(House h1, House h2) {
String s1 = h1.getHouseNumber().split("[^0-9]")[0];
String s2 = h2.getHouseNumber().split("[^0-9]")[0];
return s1.compareTo(s2);
}
}
You need to add some better handling of your cases. The above comparator says, that h1
is less than h2
when it begins with a smaller number and vise versa. For this comparator 12A
is equal 12B
but it's up to you.
@SortComparator(HouseComparator.class)
List<House> findByHouseNumber(Pageable pageable);