How to sort PageRequest on String as numeric value

前端 未结 3 1080
悲哀的现实
悲哀的现实 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:12

    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.

    0 讨论(0)
  • 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");
     }
    
    0 讨论(0)
  • 2021-01-12 01:26

    So basically you need to do two things:

    1. Implement custom comparator,
    2. Annotate the entity class.

    Ad.1.

    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.

    Ad.2.

    @SortComparator(HouseComparator.class)
    List<House> findByHouseNumber(Pageable pageable);
    
    0 讨论(0)
提交回复
热议问题