【问题标题】:@SqlResultSetMapping unknown columns referenced in entity mapping@SqlResultSetMapping 实体映射中引用的未知列
【发布时间】:2021-12-22 03:40:22
【问题描述】:

我正在尝试使用原生 SQL 查询仅将某些字段映射到实体对象:

@NamedNativeQuery(name = "CustomerEntity.findOnlyNameAndPhoneFromCustomer", query = "select customer_name, customer_email from customer",
        resultSetMapping = "nativeMapping")

@SqlResultSetMappings(value = {
@SqlResultSetMapping(name = "nativeMapping",
entities = {
@EntityResult(
     entityClass = CustomerEntity.class,
     fields = {
     @FieldResult(name = "name", column = "customer_name"),
     @FieldResult(name = "email", column = "customer_email")
     }
)})})
@Entity
class CustomerEntity {
  //getter and setter fields
 @Column(name="customer_name")
 private String name;
 @Column(name="customer_email")
 private String email;
 @Column(name="address")
 private String adddress;
@Id
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
@Access(AccessType.PROPERTY)
@Column(columnDefinition = "VARCHAR(36)", name = "customer_guid")
@Type(type = "uuid-char")
 private UUID guid;
 @Embedded
 private AuditFields audit;
}

存储库:

@Query(nativeQuery = true)
List<CustomerEntity> findOnlyNameAndPhoneFromCustomer();

我不想将customer 表中存在的所有字段都映射到CustomerEntity,我只是投影某些字段。

这给了我这样的错误:

17:44:37.841 [ERROR] o.h.e.j.s.SqlExceptionHelper - The column name address2_6_0_ is not valid.

我的表中没有名为address2_6_0_的列,但是有一个名为address的列,为什么这里要重命名和引用地址列?

我只引用customer_namecustomer_email

发生了什么事?

谢谢。

【问题讨论】:

  • 您的查询为空! @Query(nativeQuery = true)
  • @SimonMartinelli 它在@NamedNativeQuery

标签: spring-boot hibernate jpa spring-data-jpa hibernate-mapping


【解决方案1】:

entities 用于“映射到实体”。

@EntityResult:

如果使用此注解,SQL 语句应选择映射到实体对象的所有列。

因此,您应该使用classes@ConstructorResult 来“映射到DTO”。


@NamedNativeQuery(name = "CustomerEntity.findOnlyNameAndPhoneFromCustomer",
    query = "select customer_name, customer_email from customer",
    resultSetMapping = "nativeMapping")

@SqlResultSetMappings(value = {
    @SqlResultSetMapping(name = "nativeMapping",
        classes = @ConstructorResult(columns = { @ColumnResult(name = "customer_name"), @ColumnResult(name = "customer_email") },
            targetClass = CustomerEntity.class)) })
@Entity
public class CustomerEntity {

    public CustomerEntity() {
    }

    public CustomerEntity(String name, String email) {
        this.name = name;
        this.email = email;
    }
    ...
}

【讨论】:

  • 这不是我想做的。使用@EntityResult 的全部意义在于我可以选择性地初始化某些列。并避免使用@ConstructorResult
  • 我的观点是,如果不定义构造函数,就无法设置 DTO 变量。为什么我实际上不能使用其他方法(例如设置 DTO 值的 setter)
  • 您可以使用ResultTransformer
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-22
  • 1970-01-01
  • 2012-07-12
  • 2019-10-10
  • 2014-02-14
  • 1970-01-01
相关资源
最近更新 更多