I have a bidirectional mapping in Spring Boot:
Company.class
...
private Integer id;
private String nameC;
@OneToMany
private List<Employee> employees;
...
Employee.class
...
private Integer id;
private String nameE;
@ManyToOne
private Company company;
...
Now I want to make mapping with map struct to these DTOs
CompanyDTO
private Integer id;
private String nameC;
private List<EmployeeDTO> employees;
EmployeeDTO
private Integer id;
private String nameE;
private Integer company; // so this should be Company ID
MapCompany
Company toCompany(CompanyDTO cDto)
CompanyDTO toCompanyDTO(Company c)
MapEmployee
Employee toEmployee(EmployeeDTO eDto)
EmployeeDTO toEmployeeDTO(Employee emp)
@Mapping(target = "company.id", source = "eDto.company")
List<Employee> toEmployee(List<EmployeeDTO> eDto)
@Mapping(target = "company", source = "emp.company.id")
List<EmployeeDTO> toEmployeeDTO(List<Employee> emp)
Now,
- First of all I can't get mapping for toEmployee and toEmployeeDTO, the error says "The type of parameter "eDto" has no property named "company"" and " The type of parameter "emp" has no property named "emp.company.id"" I suppose that this is because eDto and emp are List<>. So how can I get the "company" parameter from List<> in MapStruct?
- Later, even if I remove those mappings with lists, there is a problem because it is bidirectional relation and I can't get the CompanyId in EmployeeDTO. The error is " Ambiguous mapping methods found for mapping property "Company company" " Is there a way to do this in MapStruct or I have to use my custom mappers?
CodePudding user response:
Try this
@Named("toEmployee")
Employee toEmployee(EmployeeDTO eDto)
@Named("toEmployeeDTO")
EmployeeDTO toEmployeeDTO(Employee emp)
@IterableMapping(qualifiedByName = "toEmployee")
List<Employee> toEmployee(List<EmployeeDTO> eDto)
@IterableMapping(qualifiedByName = "toEmployeeDTO")
List<EmployeeDTO> toEmployeeDTO(List<Employee> emp)