结合以上所有答案,您可以使用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对象重载了findAll方法-基本上,仍然使用 findAll()
public interface StudentDAO extends CrudRepository<StudentEntity, Long> {
Iterable<StudentEntity> findAll(Sort sort);
}
StudentEntity
BaseEntity
包含可重复字段的扩展(也许您也想按ID排序)
@Getter
@Setter
@FieldDefaults(level = AccessLevel.PRIVATE)
@Entity
class StudentEntity extends BaseEntity {
String firstName;
String surname;
}
最后,其服务和用法SORT_BY_CREATED_AT_DESC
可能不仅会在中使用StudentService
。
@Service
class StudentService {
@Autowired
StudentDAO studentDao;
Iterable<StudentEntity> findStudents() {
return this.studentDao.findAll(SORT_BY_CREATED_AT_DESC);
}
}
List<StudentEntity> findAllByOrderByIdAsc();
。添加返回类型并删除多余的公共修饰符也是一个好主意;)