我正在使用 Spring Data,我的 DAO 看起来像这样
public interface StudentDAO extends JpaRepository<StudentEntity, Integer> {
public findAllOrderByIdAsc(); // I want to use some thing like this
}
在上面的代码中,注释行显示了我的意图。 spring Data 可以提供内置功能吗 使用这样的方法通过 ASC/DESC 查找按某列排序的所有记录?
public interface StudentDAO extends JpaRepository<StudentEntity, Integer> {
public List<StudentEntity> findAllByOrderByIdAsc();
}
上面的代码应该可以工作。我正在使用类似的东西:
public List<Pilot> findTop10ByOrderByLevelDesc();
它返回 10 行最高级别。
重要: 既然我被告知很容易错过这个答案的关键点,这里有一点澄清:
findAllByOrderByIdAsc(); // don't miss "by"
^
AFAIK,我认为直接方法命名查询不可能做到这一点。但是,您可以使用内置的排序机制,使用
Sort
类。存储库有一个 findAll(Sort)
方法,您可以将 Sort
的实例传递给该方法。例如:
import org.springframework.data.domain.Sort;
@Repository
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentDAO studentDao;
@Override
public List<Student> findAll() {
return studentDao.findAll(sortByIdAsc());
}
private Sort sortByIdAsc() {
return new Sort(Sort.Direction.ASC, "id");
}
}
简单的方法:
repository.findAll(Sort.by(Sort.Direction.DESC, "colName"));
请查看 Spring Data JPA - 参考文档,第 5.3 节。查询方法,特别是第 5.3.2 节。查询创建,位于“表 3. 方法名称中支持的关键字”(截至 2019 年 5 月 3 日的链接)。
我认为它正是您所需要的,并且与您所说的相同的查询应该有效......
是的,您可以使用 Spring Data 中的查询方法进行排序。
例如:使用 id 字段的值进行升序或降序排列。
代码:
public interface StudentDAO extends JpaRepository<StudentEntity, Integer> {
public findAllByOrderByIdAsc();
}
替代解决方案:
@Repository
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentDAO studentDao;
@Override
public List<Student> findAll() {
return studentDao.findAll(orderByIdAsc());
}
private Sort orderByIdAsc() {
return new Sort(Sort.Direction.ASC, "id")
.and(new Sort(Sort.Direction.ASC, "name"));
}
}
Spring数据排序:排序
我尝试在这个示例中向您展示一个完整的示例来个性化您的 OrderBy 排序
import java.util.List;
import org.springframework.data.domain.Page;
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<User, Long> {
List <User> findAllWithCustomOrderBy(Sort sort);
}
您将使用这个示例: 动态构建 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);
}
}
对于 Spring Boot 3,您的 Repository 应该实现 JpaRepository,并且您应该按如下方式定义排序:
Sort sortBy = Sort.by(Sort.Direction.DESC, "id");
使用方法:
repository.findAll(sortBy);
结合上面的所有答案,您可以使用 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);
}
}
Sort sortBy = Sort.by(new Sort.Order(Sort.Direction.ASC, "name").ignoreCase());
repository.findAll(sortBy);