简体   繁体   中英

Mapping to DTO bidirectional entities in SpringBoot with MapStruct

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,

  1. 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?
  2. 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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM