春季数据分页JPA(极限和偏移)
发布时间:2020-12-14 05:28:14 所属栏目:Java 来源:网络整理
导读:我希望用户能够在查询方法中指定限制(返回的大小)和偏移量(返回的第一条记录/索引). 这是我没有任何分页功能的类. 我的实体: @Entitypublic Employee { @Id @GeneratedValue(strategy=GenerationType.AUTO) private int id; @Column(name="NAME") private S
我希望用户能够在查询方法中指定限制(返回的大小)和偏移量(返回的第一条记录/索引).
这是我没有任何分页功能的类. @Entity public Employee { @Id @GeneratedValue(strategy=GenerationType.AUTO) private int id; @Column(name="NAME") private String name; //getters and setters } 我的仓库: public interface EmployeeRepository extends JpaRepository<Employee,Integer> { @Query("SELECT e FROM Employee e WHERE e.name LIKE :name ORDER BY e.id") public List<Employee> findByName(@Param("name") String name); } 我的服务界面: public interface EmployeeService { public List<Employee> findByName(String name); } 我的服务实现: public class EmployeeServiceImpl { @Resource EmployeeRepository repository; @Override public List<Employee> findByName(String name) { return repository.findByName(name); } } 现在我试图提供支持偏移和限制的分页功能. 我的“新”存储库具有可分页参数: public interface EmployeeRepository extends JpaRepository<Employee,Integer> { @Query("SELECT e FROM Employee e WHERE e.name LIKE :name ORDER BY e.id") public List<Employee> findByName(@Param("name") String name,Pageable pageable); } 我的“新”服务界面有两个附加参数: public interface EmployeeService { public List<Employee> findByName(String name,int offset,int limit); } 我的“新”服务实现: public class EmployeeServiceImpl { @Resource EmployeeRepository repository; @Override public List<Employee> findByName(String name,int limit) { return repository.findByName(name,new PageRequest(offset,limit); } } 这不是我想要的. PageRequest指定页面和大小(页面和页面的大小).现在指定大小正是我想要的,但是,我不想指定起始页面#,我希望用户能够指定起始记录/索引.我想要类似的东西 public List<Employee> findByName(String name,int limit) { TypedQuery<Employee> query = entityManager.createQuery("SELECT e FROM Employee e WHERE e.name LIKE :name ORDER BY e.id",Employee.class); query.setFirstResult(offset); query.setMaxResults(limit); return query.getResultList(); } 特别是setFirstResult()和setMaxResult()方法.但是我不能使用这个方法,因为我想使用Employee存储库接口. (或者实际上是通过entityManager定义查询更好)?无论如何,是否有一种方法来指定偏移而不使用entityManager?提前致谢! 解决方法
你可能不能用spring数据jpa来这个.如果偏移量非常小,您可能会在检索后从查询中删除前X个语句.
否则,您可以将页面大小定义为偏移量,并从第1页开始. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |