【问题标题】:MapStruct: How to use mapper to map View Objects with Composite Key JPA?MapStruct:如何使用映射器使用复合键 JPA 映射视图对象?
【发布时间】:2020-05-08 11:13:59
【问题描述】:

我有如下目标实体:

public class ApplicationUsage {
    @Id
    private ApplicationUsagePK appUsage;    //Guid  No documentation available.
    private String name;
    .
    .
    public ApplicationUsage(String id, Integer compId) {
       this.appUsage = new ApplicationUsagePK(id, compId); //This is present in ApplicationUsagePK initiated here which acts are composite key
    }

源对象如下:

public class ApplicationUsage {

    @SerializedName("id")
    @Expose
    private String id;
    @SerializedName("name")
    @Expose
    private String name;

我需要将源对象的 ID 映射到 applicationUsage(String id 并且 CompID 来自其他变量,它需要映射到 applicationUsage(.., Integer compId) em>

上述类或映射器需要进行哪些更改才能实现相同的效果?

以下是当前映射器:

@Mapper
public interface ApplicationUsageMapper {
    ApplicationUsageMapper MAPPER = Mappers.getMapper( ApplicationUsageMapper.class );

    ApplicationUsage entityToDao(com.inte.meow.vo.computer.ApplicationUsage source);
}

不好的方式:

我使用了不好的方法来解决这个问题,你可以理解以下内容:

ApplicationUsage aUsage = ApplicationUsageMapper.MAPPER.entityToDao(agreement.getBody());
aUsage.initiateApplicationUsage(agreement.getBody().getId(), compId);

【问题讨论】:

    标签: jpa mapstruct


    【解决方案1】:

    您可以使用@Context 注释来做到这一点

    @Mapper
    public interface ApplicationUsageMapper {
        ApplicationUsageMapper MAPPER = Mappers.getMapper( ApplicationUsageMapper.class );
    
        @Mapping(target = "appUsage", source = "source", qualifiedByName = "getAppUsage")
        ApplicationUsage entityToDao(com.inte.meow.vo.computer.ApplicationUsage source, @Context Integer compId);
    
        @Named("getAppUsage")
        default ApplicationUsagePK toAppUsage(com.inte.meow.vo.computer.ApplicationUsage source, @Context Integer compId) {
            return new ApplicationUsagePK (source.getId(), compId));
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-01-18
      • 2021-02-17
      • 2023-04-03
      • 2016-10-14
      • 2021-12-01
      • 1970-01-01
      • 2017-01-30
      • 1970-01-01
      • 2014-11-02
      相关资源
      最近更新 更多