使用 ModelMapper - List 防止循环引用

Prevent circular reference with ModelMapper - List

我有一个 Json 错误,因为我的 DTO 彼此保持循环引用。

公司 DTO:

@Data
public class CompanyDTO {

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

公司国家/地区 DTO:

@Data
public class CompanyCountryDTO {

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

CompanyService 实现将 Company 列表转换为 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;
}

我想做这样的事情,但使用 ModelMapper,因为我有其他循环引用:

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

我如何从 CompanyCountryDTO 中删除公司引用,因为公司还有另一个 CompanyCountryDTO 列表?

我认为你只需要跳过“反向引用”就可以避免循环和无限递归。在这种情况下,字段 company in CompanyCountryDTO.

要使其正常工作,请将您的 ModelMapper 配置为:

modelMapper.addMappings(new PropertyMap<CompanyCountry, CompanyCountryDTO>() {
    @Override
    protected void configure() {
        // Tells ModelMapper to NOT populate company
        skip(destination.getCompany());
    }
});

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

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

所以另一个修复可能是

getConfiguration().setPreferNestedProperties(false);