首页 > 解决方案 > 使用 Mapstruct 的双向实体方法

问题描述

我有双向映射(@OneToMany Hibernate)和额外的方法来确保两个对象链接。简单的例子:

@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 (...)保持父级和子级列表之间的双向映射。

我有一个更复杂的结构,有多个嵌套的孩子,所以会考虑可扩展性。

标签: javamappingmapstructbidirectional

解决方案


MapStruct 具有集合映射策略的概念。它允许您在映射它们时使用加法器。

例如

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

    Parent toEntity(ParentDto parentDto);
}

推荐阅读