我在使用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),它将创建目标的新实例