就像在标题中一样,我正在尝试映射 2 个类,但其中一个类具有带有私有 setter 的私有属性。
public Class A {
private String propertyA;
private String propertyB;
ClassA (){
}
public String getPropertyA() {
return propertyA;
}
public void setPropertyA(String propertyA) {
this.propertyA= propertyA;
}
public String getPropertyB() {
return propertyB;
}
public void setPropertyB(String propertyB) {
this.propertyB= propertyB;
}
}
public Class B {
private String propertyA;
private String propertyB;
ClassB (String propertyB){
propertyB = propertyB;
}
public String getPropertyA() {
return propertyA;
}
public void setPropertyA(String propertyA) {
this.propertyA= propertyA;
}
public String getPropertyB() {
return propertyB;
}
void setPropertyB(String propertyB) {
this.propertyB= propertyB;
}
}
我想将对象从类 A 映射到类 B,反之亦然,唯一的区别是在从类 A 到 B 的映射中不需要设置属性 B。我已经尝试过使用以下配置:
<mapping>
<class-a map-null="false">classA</class-a>
<class-b>classB</class-b>
<field>
<a get-method="getPropertyA" set-method="setPropertyA">propertyA</a>
<b get-method="getPropertyA" set-method="setPropertyA">propertyA</b>
</field>
<field-exclude type="one-way">
<a get-method="getPropertyB" set-method="setPropertyB">propertyB</a>
<b get-method="getPropertyB">propertyB</b>
</field-exclude>
</mapping>
这给了我一个例外:无法写入类 B 的属性属性 B。这是我对私有财产的意图,但无论我做什么,例外仍然存在。我尝试添加 type="one-way" 的字段映射,但这给了我同样的例外。有没有办法用推土机做到这一点?
我认为您正在寻找的是将is-accessible="true"
添加到您对classB
propertyB
的定义中。这会通知推土机它应该直接访问该属性,而不是通过吸气器或设置器。
和 setter 遵循 bean 标准,则不必指定它们。此外,如果字段使用 Bean 标准双向映射,则根本不需要指定它。这意味着您的 XML 应该能够如下所示:
<mapping>
<class-a map-null="false">classA</class-a>
<class-b>classB</class-b>
<field-exclude type="one-way">
<a>propertyB</a>
<b is-accessible="true">propertyB</b>
</field-exclude>
</mapping>