在 Spring 使用我请求的自定义查询实现分页:
{{host}}:8080/list?page=0&size=2 and the result is OK
{{host}}:8080/list?page=0&size=3 and the result is OK
{{host}}:8080/list?page=0&size=4 and the result is OK
{{host}}:8080/list?page=0&size=1 and the result is NOT OK
{{host}}:8080/list?page=1&size=1 and the result is NOT OK
{{host}}:8080/list?page=1&size=2 and the result is NOT OK
{{host}}:8080/list?page=1&size=3 and the result is NOT OK
Controller :
@GetMapping(value = "/list")
public Page<User> list(Pageable pageable) {
try {
return userRepository.findUser(pageable);
} catch (Exception e) {
logger.error("Ex: {}", e);
return null;
}
}
存储库:
@Query(value = "select U.*, M.local as LocalM from user U inner join Morada M on M.idmorada = U.morada", nativeQuery= true)
public Page<User> findUser(Pageable pageable);
当响应不正确时会发生什么:
2020-01-03 11:34:01.659 WARN 9652 --- [nio-8080-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1054, SQLState: 42S22
2020-01-03 11:34:01.659 ERROR 9652 --- [nio-8080-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper : Unknown column 'U' in 'field list'
为什么分页属性大小和页面仅在某些场景下使用nativeQuery才起作用?
最佳答案
您还需要一个计数查询才能使分页正常工作,如下所示 -
@Query(
value = "select U.*, M.local as LocalM from user U inner join Morada M on M.idmorada = U.morada",
countQuery = "select count(*) from user U inner join Morada M on M.idmorada = U.morada",
nativeQuery = true)
Page<User> findUser(Pageable pageable);
对于 2.4 之前的 Spring JPA 版本,您需要 sql stmt 中的解决方法,例如 -
value = "select U.*, M.local as LocalM from user U inner join Morada M on M.idmorada = U.morada order by U.id \n-- #pageable\n"
#pageable 占位符告诉 Spring Data JPA 如何解析查询并注入(inject)可分页参数。 就投影而言,您可以使用接口(interface)来映射结果集,例如 -
public interface IUser {
public getId();
... getter methods from User entity
public getLocalM();
}
关于java - Spring 中使用 Pagination/Page 的表别名中的 JPA 未知列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59578002/