2

我的公司实体有一组分支机构。当我将实体转换为 DTO 时,我还想将一组分支转换为一组BranchDTO使用模型映射器。

我的实体:

public class Company {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "company_id")
    private long companyId;

    @Column(name = "company_name")
    private String companyName;

    @Column(name = "address")
    private String address;

    @OneToMany
    @JoinColumn(name="branchcompany_id", referencedColumnName="company_id")
    private Set<Branch> branches;

    ...getters setters..

 }

public class Branch {   
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "branch_id")
    private long branchId;

    @Column(name = "branch_name")
    private String branchName;
    ...
}

我想将此实体CompanyDTO与集合一起转移到BranchDTO

我的 DTO:

public class CompanyDTO {
    private long companyId;

    private String companyName;

    private String address;

    private List<BranchDTO> branches;
    ...
}


public class BranchDTO {
    private long branchId;

    private String branchName;
    ...
}

我尝试使用属性映射 - 但无法弄清楚确切的语法。以下给出了空白BranchDTO列表。

CompanyDTO newCompanyDTO = modelMapper.map(company, CompanyDTO.class);

任何帮助是极大的赞赏。

4

1 回答 1

1

ModelMapper 可以将 a 转换为List<>Set<>因此您无需进行任何配置。此外,这些属性被称为相等,并且它应该以相同的顺序工作。


我试过了,效果很好:

Company company = new Company();
Branch branch = new Branch();
branch.setBranchId(1L);
branch.setBranchName("Branch Name");
company.setBranches(new HashSet<>(Arrays.asList(branch)));
company.setAddress("Address");
company.setCompanyId(10L);
company.setCompanyName("Company Name");

ModelMapper mapper = new ModelMapper();
CompanyDTO companyDto = mapper.map(company, CompanyDTO.class);

System.out.println(companyDto);

输出

CompanyDTO(companyId=10, companyName=Company Name, address=Address, branch=[BranchDTO(branchId=1, branchName=Branch Name)])

所以检查Set:Branch元素是否为空,因为它modelmapper似乎有效。

于 2016-11-14T12:20:43.450 回答