ModelMapper:接口的全局提供程序配置

时间:2019-12-13 15:47:31

标签: java hibernate mapping modelmapper

我在使用Java模型映射器(modelmapper.org)映射DTO和ENTITY时遇到问题。最大的问题是当我尝试使用新引用更新某些实体时。例如:我试图更新用户实体并在其上设置新的公司关系。我创建了6个课程:

class UserDto {
    private Long id;
    private String username;
    private CompanyDto company;
}
class NewUserDto {
    private String username;
    private ObjectReferenceDto company;
}
class CompanyDto {
    private Long id;
    private String name;
}
class ObjectReferenceDto {
    private Long id;
}
class UserEntity {
    private Long id;
    private String username;
    private CustomerEntity customer;
}
class CustomerEntity {
    private Long id;
    private String name;
}

所以问题是,当我从数据库中获取UserEntity并填充了CustomerEntity时,我尝试像这样将NewUserDto映射到UserEntity

modelmapper.map(newUserDto, userEntity); 

,结果非常奇怪。 UserEntity的{​​{1}}引用了数据库中的旧值,但ID CustomerEntity是新的。例如,某用户的公司ID为= 1,而我尝试将其更新为属于ID = 2的客户。经过以上映射,结果是客户被指向客户1,但ID为2。

所以我想现在是否有机会在ModelMapper中创建全局提供程序,如果源是特定的接口或类(ObjectReferenceDto),它将创建目标的新实例

0 个答案:

没有答案