How to use OrderBy with findAll in Spring Data

前端 未结 7 1014
无人共我
无人共我 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:31

    Combining all answers above, you can write reusable code with BaseEntity:

    @Data
    @NoArgsConstructor
    @MappedSuperclass
    public abstract class BaseEntity {
    
      @Transient
      public static final Sort SORT_BY_CREATED_AT_DESC = 
                            Sort.by(Sort.Direction.DESC, "createdAt");
    
      @Id
      private Long id;
      private LocalDateTime createdAt;
      private LocalDateTime updatedAt;
    
      @PrePersist
      void prePersist() {
        this.createdAt = LocalDateTime.now();
      }
    
      @PreUpdate
      void preUpdate() {
        this.updatedAt = LocalDateTime.now();
      }
    }
    

    DAO object overloads findAll method - basically, still uses findAll()

    public interface StudentDAO extends CrudRepository {
    
      Iterable findAll(Sort sort);
    
    }
    

    StudentEntity extends BaseEntity which contains repeatable fields (maybe you want to sort by ID, as well)

    @Getter
    @Setter
    @FieldDefaults(level = AccessLevel.PRIVATE)
    @Entity
    class StudentEntity extends BaseEntity {
    
      String firstName;
      String surname;
    
    }
    

    Finally, the service and usage of SORT_BY_CREATED_AT_DESC which probably will be used not only in the StudentService.

    @Service
    class StudentService {
    
      @Autowired
      StudentDAO studentDao;
    
      Iterable findStudents() {
        return this.studentDao.findAll(SORT_BY_CREATED_AT_DESC);
      }
    }
    

提交回复
热议问题