table 中的 JPA 未知列与 Spring 中的 Pagination/Page 别名

JPA Unknow column in table aliases with Pagination/Page in Spring

在 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'

为什么分页属性 size 和 page 仅在某些情况下使用 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 如何解析查询并注入 pageable 参数。 就投影而言,您可以使用一个界面来映射您的结果集,例如 -

public interface IUser {
public getId();
... getter methods from User entity
public getLocalM();
}