我有两个Mappers
@Mapper(uses= {ChildMapper.class})
public abstract class ParentMapper {
@Mappings...
public abstract Parent dtoToParent(
final ParentDto dto);
@InheritConfiguration(name = "dtoToParent")
public abstract Parent updateParentFromDto(
final ParentDto dto,
final @MappingTarget Parent parent);
}
@Mapper()
public abstract class ChildMapper {
Child dtoToChild(
final ChildDto dto);
Set<Child> dtosToChilds(
final Set<ChildDto> childs);
Child updateChildFromDto(
final ChildDto dto,
final @MappingTarget Child geo);
}
在生成实现时,如何指示MapStruct在updateParentFromDto方法内部使用updateChildFromDto方法。它是使用dtosToChilds生成的,而dtosToChilds依次使用dtoToChild方法。
原因,当存在对象时,我想更新属性而不是创建新属性,而当 不存在对象创建新属性 。
答案 0 :(得分:1)
MapStruct如何(以通用方式)识别目标集中是否存在对象?
但是没有什么可以阻止您编写自己的实现。.类似这样的东西:
@Mapper()
public abstract class ChildMapper {
abstract Child dtoToChild(ChildDto dto);
abstract Child updateChildFromDto( ChildDto dto, @MappingTarget Child geo);
Set<Child> dtosToChilds(final Set<ChildDto> childs);
// NOTE the void, I don't like to return a mapping target. MapStruct calls
// update methods from update methods an regular methods from regular methods
// using both in one signature, things tend to get blurry
void updateDtosToChilds(Set<ChildDto> childs, @MappingTarget Set<Child> target){
for ( ChildDto child : childs {
Child targetChild = null;
// get matching child from target
if ( targetChild != null ) {
updateChildFromDto( child, targetChild );
}
else {
target.add( dtoToChild( child ) );
}
}
}
}
并且如上所述,请勿这样做:
@InheritConfiguration(name = "dtoToParent")
public abstract Parent updateParentFromDto(
final ParentDto dto,
final @MappingTarget Parent parent);
但是
@InheritConfiguration(name = "dtoToParent")
public abstract void updateParentFromDto(
final ParentDto dto,
final @MappingTarget Parent parent);