How to sort PageRequest on String as numeric value

前端 未结 3 1081
悲哀的现实
悲哀的现实 2021-01-12 00:51

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          


        
3条回答
  •  攒了一身酷
    2021-01-12 01:14

    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)

    1. Add a new filed in your entity with Long type
    2. for the new filed use @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;
             } 
     }
    
    1. in your service find sorted filed and change it to the newfiled
     if (Objects.nonNull(pagingRequest.getSort()) && pagingRequest.getSort().getFieldName().equals("oldField")) {
                pagingRequest.getSort().setFieldName("newField");
     }
    

提交回复
热议问题