如何在Spring Data中使用OrderBy和findAll

Pra*_*kar 246 spring spring-data spring-data-jpa

我正在使用spring数据,我的DAO看起来像

public interface StudentDAO extends JpaRepository<StudentEntity, Integer> {
    public findAllOrderByIdAsc();   // I want to use some thing like this
}
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,注释行显示了我的意图.Spring Data可以提供内置功能,使用这种方法通过ASC/DESC查找某些列的所有记录顺序吗?

Sik*_*kor 574

public interface StudentDAO extends JpaRepository<StudentEntity, Integer> {
    public List<StudentEntity> findAllByOrderByIdAsc();
}
Run Code Online (Sandbox Code Playgroud)

上面的代码应该有效.我正在使用类似的东西:

public List<Pilot> findTop10ByOrderByLevelDesc();
Run Code Online (Sandbox Code Playgroud)

它返回10行,具有最高级别.

重要提示: 由于我被告知很容易错过这个答案的关键点,这里有一点澄清:

findAllByOrderByIdAsc(); // don't miss "by"
       ^
Run Code Online (Sandbox Code Playgroud)

  • 请注意,在`OrderBy`关键字之前的小`By`会产生重大影响. (70认同)
  • 仍然不明白为什么有必要在`OrderBy`的前面增加一个额外的`By`.[文档没有说明](http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.query-creation). (4认同)
  • 为了使您的方法签名能够按照预期的方式使用Spring Data JPA,您应该包含"all"关键字,如下所示:`List <StudentEntity> findAllByOrderByIdAsc();`.添加返回类型并删除冗余的公共修饰符也是一个好主意;) (3认同)
  • @XtremeBiker从您提供的文档链接:"但是,第一个By作为分隔符来指示实际条件的开始." 此外,如果向下滚动到"3.4.5.限制查询结果"部分,实际上有一个这样的例子,但没有解释. (3认同)
  • 我同意 public 是多余的,但它可以让事情变得清晰,以防其他人必须处理你的代码。你永远不知道会是谁:PI 没有更改作者代码中方法名称以外的任何内容,因为这不是问题所在,如果有人不知道那里应该有什么,希望他们能学到新的东西。此外,它在我下面的示例中,因此他们不必搜索上帝知道在哪里,但如果您坚持,那就这样吧:)添加了“all”关键字。谢谢。 (2认同)
  • @Eduardo如果您想按两列或更多列排序,只需在 asc/desc 关键字后声明另一列,如下所示:“findAllByOrderByFirstcolAscSecondcolDesc”(未经测试,但应该有效)。但是,如果方法名称变得太长,我建议切换到“findAll(Pageable pageRequest)”并在“Pageable”中传递“Sort”对象,这样更加灵活,因为您不必为它们创建单独的方法每次使用。这样客户端就可以决定如何排序、需要多少行等。 (2认同)
  • @mattforsythe 这是正确的,这是正常的 spring 数据行为。如果您不在“find”之后放置任何 spring data 关键字(如“Top10”),它将返回所有结果。我把“All”放在那里是因为这样读起来更好。如果我没记错的话(现在无法测试)你可以在那里放任何东西,比如“findOhMyGodBy”,它的行为仍然像“findBy”或“findAllBy”。 (2认同)

Pau*_*tha 51

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");
    }
} 
Run Code Online (Sandbox Code Playgroud)

  • @ThiagoPereira你应该扩展`JpaRepository <>`如果你想使用上面的例子. (4认同)
  • `CrudRepository <>`类型中的`findAll()`方法不适用于参数(Sort) (2认同)

Tiz*_*ard 20

简单的方法:

repository.findAll(Sort.by(Sort.Direction.DESC, "colName"));
Run Code Online (Sandbox Code Playgroud)

来源:https : //www.baeldung.com/spring-data-sorting


Nar*_*chu 15

是的,您可以使用 Spring Data 中的查询方法进行排序。

例如:使用 id 字段的值进行升序或降序排列。

代码:

  public interface StudentDAO extends JpaRepository<StudentEntity, Integer> {
    public findAllByOrderByIdAsc();   
}
Run Code Online (Sandbox Code Playgroud)

替代解决方案:

    @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"));
}
}
Run Code Online (Sandbox Code Playgroud)

Spring数据排序:排序


shl*_*i33 12

请看这里:https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods

在以下部分:"表2.3.方法名称中支持的关键字"

我认为它完全符合您的要求,并且您所说的相同查询应该有效...


小智 7

我尝试在这个示例中向您展示一个完整的示例来个性化您的 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);
 }
Run Code Online (Sandbox Code Playgroud)

您将使用以下示例:动态构建 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);
        }
}
Run Code Online (Sandbox Code Playgroud)