How to use OrderBy with findAll in Spring Data

前端 未结 7 1008
无人共我
无人共我 2020-12-02 04:25

I am using spring data and my DAO looks like

public interface StudentDAO extends JpaRepository {
    public findAllOrderByIdAsc         


        
7条回答
  •  离开以前
    2020-12-02 04:42

    I try in this example to show you a complete example to personalize your OrderBy sorts

     import java.util.List;
     import org.springframework.data.domain.Page;
     import org.springframework.data.domain.Sort;
     import org.springframework.data.jpa.repository.*;
     import org.springframework.data.repository.query.Param;
     import org.springframework.stereotype.Repository;
     import org.springframework.data.domain.Sort;
     /**
     * Spring Data  repository for the User entity.
     */
     @SuppressWarnings("unused")
     @Repository
     public interface UserRepository extends JpaRepository {
     List  findAllWithCustomOrderBy(Sort sort);
     }
    

    you will use this example : A method for build dynamically a object that instance of Sort :

    import org.springframework.data.domain.Sort;
    public class SampleOrderBySpring{
     Sort dynamicOrderBySort = createSort();
         public static void main( String[] args )
         {
           System.out.println("default sort \"firstName\",\"name\",\"age\",\"size\" ");
           Sort defaultSort = createStaticSort();
           System.out.println(userRepository.findAllWithCustomOrderBy(defaultSort ));
    
    
           String[] orderBySortedArray = {"name", "firstName"};
           System.out.println("default sort ,\"name\",\"firstName\" ");
           Sort dynamicSort = createDynamicSort(orderBySortedArray );
           System.out.println(userRepository.findAllWithCustomOrderBy(dynamicSort ));
          }
          public Sort createDynamicSort(String[] arrayOrdre) {
            return  Sort.by(arrayOrdre);
            }
    
       public Sort createStaticSort() {
            String[] arrayOrdre  ={"firstName","name","age","size");
            return  Sort.by(arrayOrdre);
            }
    }
    

提交回复
热议问题