【问题标题】:JPA Unknow column in table aliases with Pagination/Page in Spring表别名中的 JPA 未知列与 Spring 中的分页/页面
【发布时间】:2020-04-21 23:36:58
【问题描述】:

在春季使用我请求的自定义查询实现分页:

{{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 的某些场景下有效?

【问题讨论】:

  • 我对 Spring 存储库(还)不太熟悉,但是当您的查询选择所有用户列以及 M.local 时,您会返回一个包含 User 实体的页面 - 我会假设框架在任何情况下都会绊倒。
  • 但是想象用户是一个投影,我需要几乎所有的 U(用户)字段和 M(Morada)一列的别名。在这种情况下达成解决方案的最佳方法是什么?

标签: java spring spring-boot jpa repository


【解决方案1】:

您还需要一个计数查询才能使分页工作,如下所示 -

@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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-15
    • 2021-01-23
    • 2012-05-25
    • 2013-09-15
    • 2023-03-15
    • 1970-01-01
    相关资源
    最近更新 更多