首页 > 解决方案 > 将本机查询转换器列休眠到 dto 中的复杂属性

问题描述

我有一个本机查询,我想将列 ( b_id, b_code, b_desc) 转换complexPropertyResultDto.

SQL

select a.id   as id,
       a.name as name,
       b.id   as b_id,
       b.code as b_code,
       b.desc as b_desc
  from a
  left join b
    on a.id = b.a_id;

ResultDto.class

public class ResultDto {

    private String id;

    private String name;

    private ComplexPropertyDto complexProperty;

    // other fields and getter|setter

}

ComplexPropertyDto.class

public class ComplexPropertyDto {

    private String id;

    private String code;

    private String desc;

    // other fields and getter|setter

}

我尝试使用列别名complexProperty.code并使用addScalar("complexProperty.code", StringType.INSTANCE)转换器。但我得到了org.hibernate.PropertyNotFoundException: Could not resolve PropertyAccess for complexProperty.code on class xxx.ResultDto

更新

如何将表中的列转换b为属性(作为注释)。complexPropertyResultDto.classEmbedded

标签: hibernatehibernate-native-query

解决方案


我不知道如何使您的特定示例工作,但我认为这是Blaze-Persistence Entity Views的完美用例。Blaze-Persistence Core 是增加对 JPA 模型领域中许多高级 SQL 概念的支持的基础。

我创建了该库以允许在 JPA 模型和自定义接口或抽象类定义模型之间轻松映射,例如 Spring Data Projections on steroids。这个想法是您以您喜欢的方式定义您的目标结构(域模型),并通过 JPQL 表达式将属性(getter)映射到实体模型。

使用 Blaze-Persistence Entity-Views 的用例的 DTO 模型可能如下所示:

@EntityView(TableAEntity.class)
public interface ResultDto {
    @IdMapping
    Long getId();
    String getName();
    ComplexPropertyDto getComplexProperty();

    @EntityView(TableBEntity.class)
    interface ComplexPropertyDto {
        @IdMapping
        Long getId();
        String getCode();
        String getDesc();
    }
}

查询是将实体视图应用于查询的问题,最简单的就是通过 id 进行查询。

ResultDto a = entityViewManager.find(entityManager, ResultDto.class, id);

Spring Data 集成允许您几乎像 Spring Data Projections 一样使用它:https ://persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#spring-data-features


推荐阅读