首页>Program>source

我有一个包含循环的对象图.我如何让JAXB处理呢? 我尝试使用 @XmlTransient 子类中的注解,但JAXB编组器仍检测到周期。

@Entity
@XmlRootElement
public class Contact {
    @Id
    private Long contactId;
    @OneToMany(mappedBy = "contact")
    private List<ContactAddress> addresses;
...
}
@Entity
@XmlRootElement
public class ContactAddress {
    @Id
    private Long contactAddressId;
    @ManyToOne
    @JoinColumn(name = "contact_id")
    private Contact contact;
    private String address;
...
}
最新回答
  • 2021-1-11
    1 #

    使用JAXB的好处是它是具有多种实现的标准运行时(就像JPA)。

    如果使用EclipseLink JAXB(MOXy),则可以使用许多扩展来处理JPA实体,包括双向关系.这是使用MOXy @XmlInverseReference批注完成的.它的作用类似于元帅上的@XmlTransient,并在元帅上填充目标与源的关系。

    http://wiki.eclipse.org/EclipseLink/Examples/MOXy/JPA/Relationships

    @Entity 
    @XmlRootElement 
    public class Contact { 
        @Id 
        private Long contactId; 
        @OneToMany(mappedBy = "contact") 
        private List<ContactAddress> addresses; 
    ... 
    } 
    @Entity 
    @XmlRootElement 
    public class ContactAddress { 
        @Id 
        private Long contactAddressId; 
        @ManyToOne 
        @JoinColumn(name = "contact_id") 
        @XmlInverseReference(mappedBy="addresses")
        private Contact contact; 
        private String address; 
    ... 
    }
    

    还可以使用其他扩展,包括对复合键和嵌入式键类的支持。

    要指定EcliseLink MOXy JAXB实现,您需要在模型类(即Contract)中包含jaxb.properties文件,并带有以下条目:

    javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
    

  • 2021-1-11
    2 #

    "非正式JAXB指南"中的此页面提供了三种处理循环的策略.它们是(摘要):

      Mark one of the reference attributes that form the cycle as @XmlTransient.

      Use @XmlID and @XmlIDREF so that the references are represented using XML ids arather than by containment.

      Use the CycleRecoverable interface to deal with cycles programmatically.

    XML

    XMLTransient几乎总是可以循环使用.您可能在字段级别具有XMLTransient,但未将XMLAccessorType指定为XmlAccessType.Field.如果未指定任何内容,则默认值为XmlAccessType.Property-或您的吸气剂.我经历过Jaxb从我错过了访问器类型注释的类中的吸气剂中选择xml元素,但仍然可以正常工作。

  • 2021-1-11
    3 #

    仅看一下本教程:jaxb将循环引用映射到XML

    我使用它并且效果很好:)

  • 2021-1-11
    4 #

    我们也可以使用XStream库,我在一个项目中尝试过它,其中JAXB给出了循环错误,但是XStream成功地处理了它

  • android:如何在SharedPreferences中存储整数数组?
  • linux:awk模式可以匹配多行吗?