1 回答

TA貢獻1942條經驗 獲得超3個贊
據我了解您想要映射Entity到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;
}
}
添加回答
舉報