Mapstruct映射带有嵌套集合的可选字段

时间:2019-12-14 12:38:52

标签: java spring-boot mapstruct

public class Parent {
    private List<Children> childrens = new ArrayList<>();
    //setter && getter
}


public class Children{

    private Employee employee;
    //setter && getter

}

public class ChildrenDTO{
    private String employeeId;
    private String employeeName;
    ......
}

public class Employee{
    private String id;
    private String name;
    .....
}



@Mapper
public interface ParentMapper{
    ParentDTO toDto(Parent parent);
}

我已经使用mapstructParent实体映射到ParentDTO,那么我的问题是: 调用employee方法时,如何在ChildrenDTO中将employeeId映射为employeeNameparrentMapper.toDto

我检查了https://github.com/mapstruct/mapstruct-examples中的一个示例,但似乎他们没有我的案子。

谢谢。

2 个答案:

答案 0 :(得分:0)

https://www.baeldung.com/mapstruct

@Mapper
public interface EmployeeMapper {
    @Mappings({
      @Mapping(target="employeeId", source="entity.id"),
      @Mapping(target="employeeName", source="entity.name")
    })
    EmployeeDTO employeeToEmployeeDTO(Employee entity);
    @Mappings({
      @Mapping(target="id", source="dto.employeeId"),
      @Mapping(target="name", source="dto.employeeName")
    })
    Employee employeeDTOtoEmployee(EmployeeDTO dto);
}

答案 1 :(得分:0)

可以有多种方法。下面提到了您更喜欢的可读性

    @Mapping(target = "targetFieldFromParentDto", source = "sourceField", qualifiedByName = "abstractMethodWithFurtherMappers")
    public abstract ParentDTO toChildrenDto(Parent parent);


    @Mapping(target = "employee", source = "employeeID"
    @Named("abstractMethodWithFurtherMappers")
    public abstract Employee abstractMethodWithFurtherMappers(Childrens ch);

如果您不想使用qualifiedByName= "methodName",也可以使用expressions示例

expression = "java(toMethodWithBody(param1, param2))"

如果您需要进一步的说明,请告诉我。