簡體   English   中英

使用 Mapstruct 的雙向實體方法

[英]Use bidirectional entity methods with Mapstruct

我有雙向映射(@OneToMany Hibernate)和額外的方法來確保 object 鏈接。 簡單的例子:

@Setter
class ParentDto {
    List<ChildDto> childList;
}

@Setter
class ChildDto {
    String text;
}

@Setter
class Parent {

    List<Child> childList;

    public void addChild(Child child) {
        childList.add(child);
        child.setParent(this);
    }
}

@Setter
class Child {
    Parent parent;
    String text;
}

映射器:

@Mapper(componentModel = "spring")
public interface TestMapper {

Parent toEntity(ParentDto parentDto);
}

生成:

public class TestMapperImpl implements TestMapper {

@Override
public Parent toEntity(ParentDto parentDto) {
    if ( parentDto == null ) {
        return null;
    }

    Parent parent = new Parent();
    parent.setChildList( childDtoListToChildList( parentDto.getChildList() ) );

    return parent;
}

protected Child childDtoToChild(ChildDto childDto) {
    if ( childDto == null ) {
        return null;
    }

    Child child = new Child();
    child.setText( childDto.getText() );

    return child;
}

protected List<Child> childDtoListToChildList(List<ChildDto> list) {
    if ( list == null ) {
        return null;
    }

    List<Child> list1 = new ArrayList<Child>( list.size() );
    for ( ChildDto childDto : list ) {
        list1.add( childDtoToChild( childDto ) );
    }
    return list1;
}

主要問題:如何強制 Mapstruct 使用parent.addChild (...)來保持父級和子級列表之間的雙向映射。

我有一個更復雜的結構,有多個嵌套的孩子,所以會考慮可擴展性。

MapStruct 具有集合映射策略的概念。 它允許您在映射它們時使用加法器。

例如

@Mapper(componentModel = "spring", collectionMappingStrategy = CollectionMappingStrategy.ADDER_PREFERRED)
public interface TestMapper {

    Parent toEntity(ParentDto parentDto);
}

經過長時間的搜索,我找到了迄今為止最好的解決方案。 它不使用特殊方法,但它允許您保持雙向連接。

@AfterMapping
default void mapBidirectional(@MappingTarget Parent parent){
    List<Child> childList = parent.getChildList();
    if (childList != null) {
        childList.forEach(child -> child.setParent(parent));
    }
}

將會

@Override
public Parent toEntity(ParentDto parentDto) {
    if ( parentDto == null ) {
        return null;
    }

    Parent parent = new Parent();

    parent.setChildList( childDtoListToChildList( parentDto.getChildList() ) );

    mapBidirectional( parent );

    return parent;
}

但是這個問題很可能還有另一種解決方案,因為雙向通信很常見,而且這種解決方案不能很好地擴展

並且不能拆分成幾個 *Mapping 類,因為你不能在 @AfterMapping 方法中使用生成的變量

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM