简体   繁体   English

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

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

I'm using Spring Boot 2.1.3.RELEASE, Spring Data JPA against a PostgreSQL database.我正在对 PostgreSQL 数据库使用 Spring Boot 2.1.3.RELEASE,Spring Data JPA。

The column names are using underscores (eg created_by ) and the entity beans normal Java camelCase createdBy , getCreatedBy() etc.列名使用下划线(例如created_by )和实体 bean 正常 Java camelCase createdBygetCreatedBy()等。

I am trying to write a native query with a projection interface, but I get back null values.我正在尝试使用投影接口编写本机查询,但我得到了null值。 Example:例子:

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

When I run this, I get back null for underscore separated columns (which work fine with non-native queries).当我运行它时,我返回 null 用于下划线分隔的列(这适用于非本机查询)。

As an experiment, I added a method in my projection called getCreated_by() and that one works fine...作为一项实验,我在我的投影中添加了一个名为getCreated_by()的方法并且该方法工作正常......

I don't want to rename all the methods in my projection to have underscores in their names because that looks ugly.我不想重命名投影中的所有方法,使其名称中包含下划线,因为这看起来很难看。 Is there a way to get native queries to work together with projections?有没有办法让本机查询与投影一起工作?

You can explicitly rename the fields in your query to match the desired method names in your projection interface.您可以显式重命名查询中的字段以匹配投影接口中所需的方法名称。

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

Just use the annotation @Column and physically set the column names as in the database. 只需使用注解@Column并像在数据库中一样物理设置列名。 Another option is to set your schema to auto create and see what schema is created automatically. 另一个选项是将架构设置为自动创建,并查看自动创建的架构。

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

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