【发布时间】:2014-09-20 10:06:55
【问题描述】:
我希望用户能够在我的查询方法中指定限制(返回金额的大小)和偏移量(返回的第一条记录/返回的索引)。
这是我没有任何分页功能的课程。 我的实体:
@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 offset, int limit) {
return repository.findByName(name, new PageRequest(offset, limit);
}
}
但这不是我想要的。 PageRequest 指定页面和大小(页面编号和页面大小)。现在指定大小正是我想要的,但是,我不想指定起始页#,我希望用户能够指定起始记录/索引。我想要类似的东西
public List<Employee> findByName(String name, int offset, 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 pagination spring-data paging