2010-08-06 46 views
1

我在JAX-RS webservice中使用JAXB(EclipseLink实现)。在XML请求中传递一个空元素时,会创建一个空对象。有没有可能将JAXB设置为创建空对象?使用JAXB创建空对象解组空元素

例XML:

<RootEntity> 
    <AttributeOne>someText</AttributeOne> 
    <EntityOne id="objectID" /> 
    <EntityTwo /> 
</RootEntity> 

当解组,创建EntityOne的一个实例,ID属性设置为“的objectID”和EntityTwo的实例与空属性创建。相反,我想EntityTwo的空对象作为一个空对象正在导致JPA持久性操作的问题。

回答

0

您可以使用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的一个现在试试这个每晚构建:

+0

我使用的EclipseLink 2.2.0,所以添加注释上我的课。不幸的是,它有一个行为,当元素为空时将元素设置为null,但具有已定义的属性。例如上例中的EntityOne现在返回一个空对象。这是预期的行为? – sdoca 2010-08-09 19:24:05

+0

这是一个错误,请参阅https://bugs.eclipse.org/322183。我们将在本周修复。要看到正确的行为,你可以在实体上使用id属性来代替属性。 – 2010-08-09 20:10:54

+0

我已经从属性更改为属性,它意味着更详细的XML,但它的工作原理。谢谢! – sdoca 2010-08-09 21:35:26