在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
主计长:
@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一起工作?
发布于 2020-01-03 04:06:46
您还需要一个计数查询以使分页工作,如下所示-
@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,您需要在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"
#分页占位符告诉Spring如何解析查询并注入分页参数。就投影而言,您可以使用一个接口来映射结果集,例如-
public interface IUser {
public getId();
... getter methods from User entity
public getLocalM();
}
https://stackoverflow.com/questions/59578002
复制