我有Object1和Object2.现在,我想映射object3,其中包含1和2的属性.
说,我有2个对象:
1. User: {first_name, last_name, id} 2. Address: {street, locality, city, state, pin, id}
现在,有了这些,我想把它映射到
User_View: {firstName, lastName, city, state}.
其中,first_name和last_name来自User对象,来自Address对象的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()
.
因此,有没有办法避免这种情况?
或者,处理这种情况的首选方法是什么?
您可以声明具有多个源参数的映射方法,并在@Mapping
注释中引用所有这些参数的属性:
@Mapper public abstract class UserViewMapper { @Mapping(source = "first_name", target = "user.firstName"), @Mapping(source = "last_name", target = "user.lastName"), public abstract UserView userAndAddressToView(User user, Address address); }
由于"city"和"state"属性名称在源和目标中匹配,因此无需映射它们.
有关更多详细信息,另请参阅参考文档中的"定义映射器"一章.