java - Spring 中使用 Pagination/Page 的表别名中的 JPA 未知列

标签 java spring spring-boot jpa repository

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

相关文章:

java - 检查数组是否已排序,返回 true 或 false

java - 有没有一种有效的方法来测试 RMI 服务器是否已启动?

java - Eclipse 编辑器允许接口(interface)中缺少 static 和 Final 关键字

spring - 从另一个应用程序使用网关

java - Spring Boot 调度程序线程随机停止

java - 在 onClick(View arg0) 中使用 Sleep(int ms)

java - Spring 启动休息 api : how to respond gracefully if Request Body is sent in incorrect format?

java - Spring Social oAuth - 重定向后出现异常

Spring安全身份验证管理器没有提供者

java - 将 Spring Boot 属性数组绑定(bind)到对象