2

I'm having a Json error because my DTO's are keeping a circular reference each other.

CompanyDTO:

@Data
public class CompanyDTO {

    private Long id;
    private String name;
    private List<CompanyCountryDTO> companyCountries;
    //getters and setters
}

CompanyCountryDTO:

@Data
public class CompanyCountryDTO {

    private Long id;
    private LocalDateTime createdAt;
    private CompanyDTO company;
    private CountryDTO country;
    //getters and setters

CompanyService implementation convert a list of Company to a list of CompanyDTO:

@Override
public List<CompanyDTO> getAllCompaniesWithCountryDTO() {
   List<Company> listCompanies = companyRep.findAll();
   return listCompanies.stream().map(this::convertToDto).collect(Collectors.toList());
}

private CompanyDTO convertToDto(Company company) {
    CompanyDTO companyWithServiceDTO = modelMapper.map(company, CompanyDTO.class);
    return companyWithServiceDTO;
}

I would like to do something like this but using ModelMapper because I have others references that are circular:

listCompanies.stream().forEach(company -> {
    if (!ObjectUtils.isEmpty(company.getCompanyCountries())) {
        company.getCompanyCountries().forEach(companyCountry -> {
           companyCountry.setCompany(null);             
        });
    }
});

How can I remove company reference from CompanyCountryDTO since company also have another list of CompanyCountryDTO?

Aldo Inácio da Silva
  • 824
  • 2
  • 14
  • 38

2 Answers2

2

I think that you just need to skip the "back reference" to avoid circularity and infinite recursion. In this case the field company in CompanyCountryDTO.

To have it work configure your ModelMapper like:

modelMapper.addMappings(new PropertyMap<CompanyCountry, CompanyCountryDTO>() {
    @Override
    protected void configure() {
        // Tells ModelMapper to NOT populate company
        skip(destination.getCompany());
    }
});
pirho
  • 11,565
  • 12
  • 43
  • 70
  • I didn't know how to skip an object in a child list. I didn't know it was just mapping the entity. Thanks. – Aldo Inácio da Silva Dec 07 '20 at 14:09
  • problem is this always skips it. even when we want don't wanna. what if i only want to skip it when mapping a CompanyDto and not when im mapping a CompanyCountryDTO ? and vise versa. – lolplayer101 Jan 21 '22 at 14:56
1

http://modelmapper.org/user-manual/configuration/ says

Prefer nested properties | Determines if the implicit mapping should map the nested properties, we strongly recommend to disable this option while you are mapping a model contains circular reference | true

So another fix might be to

getConfiguration().setPreferNestedProperties(false);
serv-inc
  • 35,772
  • 9
  • 166
  • 188