您可以使用MOXy的NullPolicy指定此行爲。您將需要創建一個DescriptorCustomizer來修改基礎映射。別擔心,它更容易比它的聲音,下面我將證明:
import org.eclipse.persistence.config.DescriptorCustomizer;
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.oxm.mappings.XMLCompositeObjectMapping;
import org.eclipse.persistence.oxm.mappings.nullpolicy.XMLNullRepresentationType;
public class RootEntityCustomizer implements DescriptorCustomizer {
@Override
public void customize(ClassDescriptor descriptor) throws Exception {
XMLCompositeObjectMapping entityTwoMapping = (XMLCompositeObjectMapping) descriptor.getMappingForAttributeName("entityTwo");
entityTwoMapping.getNullPolicy().setNullRepresentedByEmptyNode(true);
entityTwoMapping.getNullPolicy().setMarshalNullRepresentation(XMLNullRepresentationType.EMPTY_NODE);
}
}
下面是如何將定製與您的模型類關聯:
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.eclipse.persistence.oxm.annotations.XmlCustomizer;
@XmlRootElement(name="RootEntity")
@XmlCustomizer(RootEntityCustomizer.class)
public class RootEntity {
private String attributeOne;
private Entity entityOne;
private Entity entityTwo;
@XmlElement(name="AttributeOne")
public String getAttributeOne() {
return attributeOne;
}
public void setAttributeOne(String attributeOne) {
this.attributeOne = attributeOne;
}
@XmlElement(name="EntityOne")
public Entity getEntityOne() {
return entityOne;
}
public void setEntityOne(Entity entityOne) {
this.entityOne = entityOne;
}
@XmlElement(name="EntityTwo")
public Entity getEntityTwo() {
return entityTwo;
}
public void setEntityTwo(Entity entityTwo) {
this.entityTwo = entityTwo;
}
}
在莫西的下一個版本(2.2 )你將能夠通過註釋來完成此操作。
@XmlElement(name="EntityTwo")
@XmlNullPolicy(emptyNodeRepresentsNull=true,
nullRepresentationForXml=XmlMarshalNullRepresentation.EMPTY_NODE)
public Entity getEntityTwo() {
return entityTwo;
}
您可以使用的EclipseLink 2.2.0的一個現在試試這個每晚構建:
我使用的EclipseLink 2.2.0,所以添加註釋上我的課。不幸的是,它有一個行爲,當元素爲空時將元素設置爲null,但具有已定義的屬性。例如上例中的EntityOne現在返回一個空對象。這是預期的行爲? – sdoca 2010-08-09 19:24:05
這是一個錯誤,請參閱https://bugs.eclipse.org/322183。我們將在本週修復。要看到正確的行爲,你可以在實體上使用id屬性來代替屬性。 – 2010-08-09 20:10:54
我已經從屬性更改爲屬性,它意味着更詳細的XML,但它的工作原理。謝謝! – sdoca 2010-08-09 21:35:26