ChatGPT解决这个技术问题 Extra ChatGPT

如何在 Spring Data 中使用 OrderBy 和 findAll

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

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

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


W
Willi Mentzel
public interface StudentDAO extends JpaRepository<StudentEntity, Integer> {
    public List<StudentEntity> findAllByOrderByIdAsc();
}

上面的代码应该可以工作。我正在使用类似的东西:

public List<Pilot> findTop10ByOrderByLevelDesc();

它返回最高级别的 10 行。

重要提示:因为有人告诉我很容易错过这个答案的关键点,所以这里有一点澄清:

findAllByOrderByIdAsc(); // don't miss "by"
       ^

为了使您的方法签名能够按预期与 Spring Data JPA 一起使用,您应该包含“all”关键字,如下所示:List<StudentEntity> findAllByOrderByIdAsc();。添加返回类型并删除多余的 public 修饰符也是一个好主意;)
我同意 public 是多余的,但它会让事情变得清晰,以防其他人必须处理你的代码。你永远不知道它会是谁:PI 没有改变作者代码中的方法名称,因为它不是问题所在,如果有人不知道应该在那里,希望他们能学到新的东西。此外,它在我下面的示例中,因此他们不必搜索天知道在哪里,但是如果您坚持,那就这样吧:) 添加了“所有”关键字。谢谢。
请注意,OrderBy 关键字之前的小 By 会有所不同。
还是不明白为什么要在 OrderBy 前面多加一个 Bydocumentation doesn't tell about it
@XtremeBiker 从您提供的文档链接中:“但是,第一个 By 充当分隔符以指示实际标准的开始。”而且,如果你向下滚动到“3.4.5.限制查询结果”部分,实际上有这样的例子,但没有解释。
P
Paul Samsotha

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");
    }
} 

这确实可以使用 Sikor's answer below 中提到的 findAllByOrderByIdAsc() ... @Prashant 这确实应该是正确的答案
如果你想让你的存储库不那么混乱,那么在服务层中进行排序的替代方法。请记住结果大小!
CrudRepository<> 类型中的方法 findAll() 不适用于参数(排序)
@ThiagoPereira 如果您想使用上面的示例,您应该扩展 JpaRepository<>
T
TizonDife Villiard

简单的方法:

repository.findAll(Sort.by(Sort.Direction.DESC, "colName"));

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


有2个相同的答案。你的答案格式不正确
为我工作谢谢
我一直在寻找如何使用参数化顺序进行排序,所以这是最有帮助的答案。
t
t0r0X

请查看“表 3. 方法名称中支持的关键字”中的 Spring Data JPA - Reference Documentation, section 5.3. Query Methods,尤其是第 5.3.2. Query Creation 部分(截至 2019 年 5 月 3 日的链接)。

我认为它完全符合您的需求,并且与您所说的相同的查询应该可以工作...


你的链接失效了->我假设您想指向此链接:docs.spring.io/spring-data/jpa/docs/current/reference/html/…
N
Narayan Yerrabachu

是的,您可以使用 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 数据排序:Sorting


S
S. FRAJ

我尝试在此示例中向您展示一个完整的示例来个性化您的 OrderBy 排序

 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<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);
        }
}

J
J.Wincewicz

结合以上所有答案,您可以使用 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);
  }
}

非常漂亮和干净的答案!