我有对象 1 和对象 2。现在,我想用 1 和 2 的属性映射 object3。
说,我有 2 个对象:
1. User: {first_name, last_name, id}
2. Address: {street, locality, city, state, pin, id}
现在,有了这些,我想把它映射到
User_View: {firstName, lastName, city, state}.
其中,名字和姓氏将来自用户对象,城市和州来自地址对象。
现在,我的问题是,如何做到这一点?
但是,目前,我正在这样做
@Mapper
public abstract class UserViewMapper {
@Mappings({
@Mapping(source = "first_name", target = "firstName"),
@Mapping(source = "last_name", target = "lastName"),
@Mapping(target = "city", ignore = true),
@Mapping(target = "state", ignore = true)
})
public abstract UserView userToView(User user);
public UserView addressToView(UserView userView, Address address) {
if (userView == null) {
return null;
}
if (address == null) {
return null;
}
userView.setCity(address.getCity());
userView.setState(address.getState());
return userView;
}
}
但是,在这里,我必须手动将映射写入addressToView()
.
因此,有什么办法可以避免这种情况吗?
或者,处理这种情况的首选方法是什么?