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);
}
我已经使用mapstruct
将Parent
实体映射到ParentDTO
,那么我的问题是:
调用employee
方法时,如何在ChildrenDTO中将employeeId
映射为employeeName
和parrentMapper.toDto
?
我检查了https://github.com/mapstruct/mapstruct-examples中的一个示例,但似乎他们没有我的案子。
谢谢。
答案 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))"
如果您需要进一步的说明,请告诉我。