繁体   English   中英

Spring 数据 JPA 本机查询不遵循投影的命名约定

[英]Spring Data JPA native query does not follow naming convention with projections

我正在对 PostgreSQL 数据库使用 Spring Boot 2.1.3.RELEASE,Spring Data JPA。

列名使用下划线(例如created_by )和实体 bean 正常 Java camelCase createdBygetCreatedBy()等。

我正在尝试使用投影接口编写本机查询,但我得到了null值。 例子:

public class MyEntity {
    private String createdBy;
    // getters and setters etc
    // more fields here
}

public interface MyProjection {
    String getCreatedBy();
}

public interface MyRepository extends JpaRepository<MyEntity, Long> {
    @Query(value = "
       SELECT DISTINCT cool_table.* FROM cool_table INNER JOIN
       // more SQL things", nativeQuery = true
    )
    List<MyProjection> searchNative(String filter);
}

当我运行它时,我返回 null 用于下划线分隔的列(这适用于非本机查询)。

作为一项实验,我在我的投影中添加了一个名为getCreated_by()的方法并且该方法工作正常......

我不想重命名投影中的所有方法,使其名称中包含下划线,因为这看起来很难看。 有没有办法让本机查询与投影一起工作?

您可以显式重命名查询中的字段以匹配投影接口中所需的方法名称。

public interface MyProjection {
  String getCreatedBy();
}

public interface MyRepository extends JpaRepository<MyEntity, Long> {
  @Query(
    value = "SELECT cool_table.created_by AS createdBy ...",
    nativeQuery = true
  )
  List<MyProjection> searchNative(String filter);
}

只需使用注解@Column并像在数据库中一样物理设置列名。 另一个选项是将架构设置为自动创建,并查看自动创建的架构。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM