[英]What is the best way to use findAll with Pageable in Spring?
I have employee class我有员工 class
@Entity
class Employee {
@Id
Integer id;
String name;
Integer age;
}
and another class EmployeeInfo:和另一个 class EmployeeInfo:
class EmployeeInfo {
Integer id;
String name;
}
Now, I need to build a service to get a paginated list of EmployeeInfo by using findAll(Pageable pageable)
from the repository现在,我需要使用存储库中的findAll(Pageable pageable)
构建一个服务来获取 EmployeeInfo 的分页列表
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
what is the best way to do that?最好的方法是什么? I want to avoid getting the page from findAll and create a new object of EmployeeInfo then adding it to a list in a loop我想避免从 findAll 获取页面并创建一个新的 object 的 EmployeeInfo 然后将其添加到循环中的列表中
You can utilize spring-data-jpa projections .您可以使用 spring-data-jpa投影。
There are many ways to use them (open/closed projections, class or interface based, etc.), but since you already have a EmployeeInfo
class, it can be achieved by defining a new method in your repository:有很多方法可以使用它们(打开/关闭投影、class 或基于接口等),但由于您已经有一个EmployeeInfo
class,它可以通过在您的存储库中定义一个新方法来实现:
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
Page<EmployeeInfo> getAllBy(Pageable pageable);
}
Note that your projection DTO class properties must exactly match properties in the aggregate root (entity class).请注意,您的投影 DTO class 属性必须与聚合根(实体类)中的属性完全匹配。
Also reference documentation suggest to define .equals()
and .hashcode()
methods.参考文档还建议定义.equals()
和.hashcode()
方法。
Other methods can be found in the official documentation .其他方法可以参考官方文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.