I have tried implementing JPA Repository with Spring Boot it works fine. Now if i try to implement custom query in interface which extends JpaRepository using @Query Annotation it works fine returns List of beans.(using NamedQuery). Now when i try to use pagination for custom method/query it doesn't work.
Code :
Controller :
@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";
}
Service
@Override
public Page<Employee> getAllEmployeesUsingNamedQueryWithPaging(Integer
pageNumber) {
PageRequest pageRequest =
new PageRequest(pageNumber - 1, PAGE_SIZE,
Sort.Direction.ASC, "id");
return
employeeDao.getAllEmployeesUsingNamedQueryWithPaging(pageRequest);
}
Dao
@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);
}
NamedQuery
<?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>
Exception : java.lang.IllegalArgumentException: Type specified for TypedQuery [java.lang.Long] is incompatible with query return type [class com.mobicule.SpringBootJPADemo.beans.Employee]
I just want to have pagination functionality provided by Spring JPA Repository for custom methods and query also. How can I achieve this?
@Query("from Employee")
does it change the behavior? also the @Transactional on the repository is redundant. Also for queries this simple you'd be better off just using thefindAll
the repository already has. – xenoterracidePage<Employee>
you should not get a List, you should only get a List if you ask for a List or a sub interface of List (such as Iterable) – xenoterracide