java dto 生成_java – 从多个源DTO映射到一个目标

本文介绍了如何使用MapStruct将包含DtoA和DtoB的Dto类映射到一个包含AB的Entity类。在尝试直接映射时遇到了问题,因为MapStruct会为每个目标属性创建新的AB实例。通过创建一个额外的方法toAB来解决这个问题,实现了正确的映射逻辑。
摘要由CSDN通过智能技术生成

使用MapStruct.举个例子:

class Dto {

DtoA a;

DtoB b;

}

class DtoA {

Long id;

//...

}

class DtoB {

Long id;

//...

}

class Entity {

AB ab;

}

如何将DtoA和DtoB映射到AB?

我试过了:

public abstract Entity toEntity(Dto dto);

@Mappings({

@Mapping(source = "a", target = "ab.a"),

@Mapping(source = "b", target = "ab.b")

)}

public abstract AB toABEntity(DtoA a, DtoB b);

已生成Altough代码*,未调用方法toABEntity.

*糟糕的是,因为它首先设置“a”但是然后设置“b”会创建一个新的“ab”实例,因此“a”会丢失.

最佳答案 据我了解你想要将实体映射到Dto并将两个字段Dto.a和Dto.b组合到单个字段Entity.ab中.

通常当你尝试这样做时:

@Mapper

public interface TestMapper {

@Mappings({

@Mapping(source = "a.id", target = "ab.aId", qualifiedByName = "toAB"),

@Mapping(source = "b.id", target = "ab.bId", qualifiedByName = "toAB"),

})

Entity toEntity(Dto dto);

}

对于在ab内具有目标属性的每个@Mapping,生成的映射器覆盖ab实例.这显然是一个错误,并且在MapStructs GitHub上有一张票:https://github.com/mapstruct/mapstruct/issues/1148

但有一个解决方法:

@Mapper

public interface TestMapper {

@Mappings({

@Mapping(source = "dto", target = "ab", qualifiedByName = "toAB"),

})

Entity toEntity(Dto dto);

@Mappings({

@Mapping(target = "aId", source = "a.id"),

@Mapping(target = "bId", source = "b.id"),

})

AB toAB(Dto dto);

}

我认为AB类是:

class AB {

public Long aId;

public Long bId;

}

生成的映射器代码:

public class TestMapperImpl implements TestMapper {

@Override

public Entity toEntity(Dto dto) {

if ( dto == null ) {

return null;

}

Entity entity = new Entity();

entity.ab = toAB( dto );

return entity;

}

@Override

public AB toAB(Dto dto) {

if ( dto == null ) {

return null;

}

AB aB = new AB();

Long id = dtoBId( dto );

if ( id != null ) {

aB.bId = id;

}

Long id1 = dtoAId( dto );

if ( id1 != null ) {

aB.aId = id1;

}

return aB;

}

private Long dtoBId(Dto dto) {

if ( dto == null ) {

return null;

}

DtoB b = dto.b;

if ( b == null ) {

return null;

}

Long id = b.id;

if ( id == null ) {

return null;

}

return id;

}

private Long dtoAId(Dto dto) {

if ( dto == null ) {

return null;

}

DtoA a = dto.a;

if ( a == null ) {

return null;

}

Long id = a.id;

if ( id == null ) {

return null;

}

return id;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值