您可以使用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