我尝试使用 Spring Boot 实现 JPA 存储库,它工作正常。现在,如果我尝试在使用@Query Annotation 扩展 JpaRepository 的接口中实现自定义查询,它可以正常返回 bean 列表。(使用 NamedQuery)。现在,当我尝试将分页用于自定义方法/查询时,它不起作用。
代码 :
控制器 :
@RequestMapping("/custompages/{pageNumber}")
public String getAllEmployeesUsingNamedQueryWithPaging(@PathVariable Integer pageNumber,Model model)
{
Page<Employee> page = employeeService.getAllEmployeesUsingNamedQueryWithPaging(pageNumber);
System.out.println("current page "+page);
System.out.println("current page content"+page.getContent());
int current = page.getNumber() + 1;
int begin = Math.max(1, current - 5);
int end = Math.min(begin + 10, page.getTotalPages());
model.addAttribute("empList", page.getContent());
model.addAttribute("empPages", page);
model.addAttribute("beginIndex", begin);
model.addAttribute("endIndex", end);
model.addAttribute("currentIndex", current);
return "employeeWorkbench";
}
服务
@Override
public Page<Employee> getAllEmployeesUsingNamedQueryWithPaging(Integer
pageNumber) {
PageRequest pageRequest =
new PageRequest(pageNumber - 1, PAGE_SIZE,
Sort.Direction.ASC, "id");
return
employeeDao.getAllEmployeesUsingNamedQueryWithPaging(pageRequest);
}
道
@Transactional
public interface EmployeeDao extends JpaRepository<Employee, Long>{
@Query(name="HQL_GET_ALL_EMPLOYEE_BY_ID")//Works Fine
public List<Employee> getEmpByIdUsingNamedQuery(@Param("empId") Long
empId);
@Query(name="HQL_GET_ALL_EMPLOYEE") //throws exception
public Page<Employee> getAllEmployeesUsingNamedQueryWithPaging(Pageable
pageable);
}
命名查询
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD
3.0//EN"
"http://hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<query name="HQL_GET_ALL_EMPLOYEE">from Employee</query>
<query name="HQL_GET_ALL_EMPLOYEE_BY_ID">from Employee where id =
:empId</query>
</hibernate-mapping>
异常:java.lang.IllegalArgumentException:为 TypedQuery [java.lang.Long] 指定的类型与查询返回类型 [class com.mobicule.SpringBootJPADemo.beans.Employee] 不兼容
我只想让 Spring JPA Repository 为自定义方法和查询提供分页功能。我怎样才能做到这一点?