我有2个班A
和B
,他们都有一家公司。 A
的公司获得的信息比B
的公司(Company
有id
而CNCompany
没有)更多。我想用orika映射所有字段。如果对象的所有字段都为null,我希望该对象为null!
我试图通过单元测试来表达这一点。要做到这一点需要做些什么?
public class A {
private Company company;
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
}
public class B {
private CNCompany company;
public CNCompany getCompany() {
return company;
}
public void setCompany(CNCompany company) {
this.company = company;
}
}
public class Company {
private Id id;
private AccountId accountId;
public Id getId() {
return id;
}
public void setId(Id id) {
this.id = id;
}
public AccountId getAccountId() {
return accountId;
}
public void setAccountId(AccountId accountId) {
this.accountId = accountId;
}
}
public class CNCompany {
private AccountId accountId
public AccountId getAccountId() {
return accountId;
}
public void setAccountId(AccountId accountId) {
this.accountId = accountId;
}
}
public class MyMapper extends ConfigurableMapper {
@Override
protected void configure(MapperFactory factory) {
factory.classMap(A.class, B.class) //
.mapNulls(false).mapNullsInReverse(false) //
.byDefault() //
.register();
}
}
@Test
public void testMap() throws Exception {
A a = new A();
Company company = new Company();
Id id = new Id();
id.setValue("1");
company.setId(id);
a.setCompany(company);
MyMapper myMapper = new MyMapper();
B outcome = myMapper.map(a, B.class);
assertThat(outcome.getCompany(), is(nullValue()));
}
答案 0 :(得分:0)
如果我理解正确,如果getCompany
对象仅包含空值,则希望null
返回Company
。
在Orika中,您可以使用custom converter控制转换。对于您的示例,可能类似于:
public class CompanyConverter extends CustomConverter<Company, CNCompany> {
public CNCompany convert(Company source, Type<? extends CNCompany> destinationType) {
if (isNothingButNulls(source)) {
return null;
}
final CNCompany newCompany = new CNCompany();
// do your thing
return newCompany;
}
}
我从来没有写过可以返回CustomConverter
的{{1}}所以我不是百分之百确定它会起作用但应该这样。请注意,仍需要注册转换器。我链接的文档显示了如何根据转换器所需的级别进行注册。