【问题标题】:JAXB EclipseLink Moxy: cycle is detected in the object graphJAXB EclipseLink Moxy:在对象图中检测到循环
【发布时间】:2014-12-26 23:29:44
【问题描述】:

我在编组具有双向关系的对象图时遇到了一种奇怪的行为。

错误信息是:

异常 [EclipseLink-25037](Eclipse 持久性服务 - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.XMLMarshalException

异常描述:在对象图中检测到循环。这 将导致无限循环: com.moxytest.Cycle$Doc@27f723 -> com.moxytest.Cycle$Pub@670b40af -> com.moxytest.Cycle$Agree@4923ab24 -> com.moxytest.Cycle$Agen@44c8afef -> com.moxytest.Cycle$Acc@7b69c6ba -> com.moxytest.Cycle$Med@46daef40 -> com.moxytest.Cycle$Pag@12f41634 -> com.moxytest.Cycle$Doc@27f723

异常消息中的对象图似乎没有按处理顺序排列。调试 XPathObjectBuilder 显示,在 cycleDetectionStack 上,对象按以下顺序推送:

com.moxytest.Cycle$Doc
com.moxytest.Cycle$Pag
com.moxytest.Cycle$Med
com.moxytest.Cycle$Acc
com.moxytest.Cycle$Agen
com.moxytest.Cycle$Agree
com.moxytest.Cycle$Pub 

我不明白为什么会抛出异常,因为我认为我可以使用 @XmlInverseReference。该问题仅发生在更复杂的对象图上。代码如下:

import java.io.StringReader;
import java.io.StringWriter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import org.eclipse.persistence.jaxb.JAXBContext;
import org.eclipse.persistence.jaxb.MarshallerProperties;
import org.eclipse.persistence.oxm.MediaType;
import org.eclipse.persistence.oxm.annotations.XmlInverseReference;

public final class Cycle {

    private static JAXBContext JAXB_CONTEXT;

    static {
        try {
            JAXB_CONTEXT = (JAXBContext) JAXBContext.newInstance(Doc.class);
        } catch (JAXBException ex) {
            ex.printStackTrace();
        }
    }

    @XmlTransient
    @XmlAccessorType(XmlAccessType.PROPERTY)
    public static abstract class Entity {

        private String id;

        @XmlElement
        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

    }

    @XmlRootElement
    public static class Doc extends Entity {

        private Pag pag;

        private Pub pub;

        @XmlElement
        @XmlInverseReference(mappedBy = "doc")
        public Pag getPag() {
            return pag;
        }

        public void setPag(Pag pag) {
            this.pag = pag;
        }

        @XmlElement
        @XmlInverseReference(mappedBy = "docs")
        public Pub getPub() {
            return pub;
        }

        public void setPub(Pub pub) {
            this.pub = pub;
        }

    }

    @XmlRootElement
    public static class Acc extends Entity {

        private Agen agen;

        @XmlElement
        public Agen getAgen() {
            return agen;
        }

        public void setAgen(Agen agen) {
            this.agen = agen;
        }

    }

    @XmlRootElement
    public static class Med extends Entity {

        private Pag pag;

        private Acc acc;

        @XmlElement
        @XmlInverseReference(mappedBy = "meds")
        public Pag getPag() {
            return pag;
        }

        public void setPag(Pag pag) {
            this.pag = pag;
        }

        @XmlElement
        public Acc getAcc() {
            return acc;
        }

        public void setAcc(Acc acc) {
            this.acc = acc;
        }

    }

    @XmlRootElement
    public static class Pag extends Entity {

        private Doc doc;

        private List<Med> meds = new ArrayList<>();

        public void setDoc(Doc doc) {
            this.doc = doc;
        }

        @XmlElement
        @XmlInverseReference(mappedBy = "pag")
        public Doc getDoc() {
            return doc;
        }

        @XmlElement
        @XmlInverseReference(mappedBy = "pag")
        public List<Med> getMeds() {
            return meds;
        }

        public void setMeds(List<Med> meds) {
            this.meds = meds;
        }

    }

    @XmlRootElement
    public static class Pub extends Entity {

        private List<Doc> docs;

        private Agree agree;

        public List<Doc> getDocs() {
            return docs;
        }

        @XmlElement
        @XmlInverseReference(mappedBy = "pub")
        public void setDocs(List<Doc> docs) {
            this.docs = docs;
        }

        @XmlElement
        @XmlInverseReference(mappedBy = "pub")
        public Agree getAgree() {
            return agree;
        }

        public void setAgree(Agree agree) {
            this.agree = agree;
        }

    }

    @XmlRootElement
    public static class Agree extends Entity {

        private Pub pub;

        private Agen agen;

        @XmlElement
        @XmlInverseReference(mappedBy = "agree")
        public Pub getPub() {
            return pub;
        }

        public void setPub(Pub pub) {
            this.pub = pub;
        }

        @XmlElement
        @XmlInverseReference(mappedBy = "agrees")
        public Agen getAgen() {
            return agen;
        }

        public void setAgen(Agen agen) {
            this.agen = agen;
        }

    }

    @XmlRootElement
    public static class Agen extends Entity {

        private List<Agree> agrees;

        @XmlElement
        @XmlInverseReference(mappedBy = "agen")
        public List<Agree> getAgrees() {
            return agrees;
        }

        public void setAgrees(List<Agree> agrees) {
            this.agrees = agrees;
        }

    }

    public static void main(String[] args) throws JAXBException {
        Pag pag = new Pag();

        Med med = new Med();
        med.setPag(pag);
        pag.getMeds().add(med);

        Doc doc = new Doc();
        pag.setDoc(doc);
        doc.setPag(pag);

        Pub pub = new Pub();
        pub.setDocs(Arrays.asList(doc));
        doc.setPub(pub);

        Agree agree = new Agree();
        agree.setPub(pub);
        pub.setAgree(agree);

        Agen agen = new Agen();
        agen.setAgrees(Arrays.asList(agree));
        agree.setAgen(agen);

        Acc acc = new Acc();
        acc.setAgen(agen);
        med.setAcc(acc);

        String marshal = marshal(doc);
        System.err.println(marshal);
        Doc ud = unmarshal(Doc.class, marshal);
        String marshal2 = marshal(ud);
        System.err.println("\n\n" + marshal2);
        System.err.println("Equals? " + marshal.equals(marshal2));
    }

    public static String marshal(Object toMarshal) throws JAXBException {
        Marshaller marshaller = JAXB_CONTEXT.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
//        marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_XML);
        marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON);
        StringWriter sw = new StringWriter();
        marshaller.marshal(toMarshal, sw);
        return sw.toString();
    }

    @SuppressWarnings("unchecked")
    public static <T> T unmarshal(Class<T> unmarshallingClass, String str) throws JAXBException {
        Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller();
//        unmarshaller.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_XML);
        unmarshaller.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON);
        return (T) unmarshaller.unmarshal(new StringReader(str));
    }

}

如果我在 Pub 类的 setDocs() 中删除 @XMLElement,它会起作用。但是后来我在编组 Pub 时丢失了 docs 对象。

你能帮忙吗?

===============更新

EclipseLink 的 XMLInverseReference 实现不考虑传递循环。在编组期间,它创建一个 cycleDetectionStack 放置所有编组的对象。如果遇到 XMLInverseReference,它会尝试通过从 cycleDetectionStack - 2 中获取对象来找到所有者。这适用于对象之间的直接循环,但不适用于像 A --> B --> C --> A 这样的传递循环。

查看源代码,我发现了一种使其适用于传递循环的简单方法。我所要做的就是遍历整个cycleDetectionStack:

XMLCompositeCollectionMappingNodeValue:

if ((isInverseReference || xmlCompositeCollectionMapping.getInverseReferenceMapping() != null) && size >= 2) {
    //Object owner = marshalRecord.getCycleDetectionStack().get(size - 2);
    // Bugfix InverseRef has no effect on "transitive" references within object graph
    CycleDetectionStack cycleDetectionStack = marshalRecord.getCycleDetectionStack();
    for (Object stackedObj : cycleDetectionStack) {
        try {
            if (cp.contains(stackedObj, collection, session)) {
                return false;
            }
        } catch (ClassCastException e) {
            // For Bug #416875
        }
    }
}

第二个类是 XMLCompositeObjectMappingNodeValue ,其解法完全相同:

if ((isInverseReference || xmlCompositeObjectMapping.getInverseReferenceMapping() != null) && objectValue != null && size >= 2) {
    //Object owner = marshalRecord.getCycleDetectionStack().get(size - 2);
    // Bugfix InverseRef has no effect on "transitive" references within object graph
    CycleDetectionStack cycleDetectionStack = marshalRecord.getCycleDetectionStack();
    for (Object stackedObj : cycleDetectionStack) {
        if (objectValue.equals(stackedObj)) {
            return false;
        }
    }
}

也许开发商有充分的理由只看所有者。至于我,我不知道为什么要忍受这个缺点。我们有一个大型域模型,其中所有实体都通过 json 进行转码。从那以后我们没有遇到任何错误。

【问题讨论】:

  • 此页面:ibm.com/developerworks/rational/library/… 声明“当关系超出两个实体时,[XmlInverseReferece] 不起作用”。当然,这对我也不起作用,而且我的关系中只有两个实体。 :(
  • 这很有趣。提到的链接准确地描述了我必须经历的痛苦。 XMLIDREF 和容器对象的解决方法对我来说不是解决方案。我最终调查了 eclipse 链接源代码,发现它的实现存在一个缺陷,可以通过考虑传递循环的方式来修复。修复是如此微不足道,以至于我想知道开发人员是否有充分的理由。但是我找不到任何问题,为什么我的修复和解决方案适用于对象以 json 格式转码的大型实体域。查看我的更新

标签: jaxb eclipselink moxy jaxb2


【解决方案1】:

在 JPA 模型层中,循环引用和外键引用可能会将 JSON 序列化转换为循环结构并不少见。这称为 JSOG,您的 JSON 结构中有循环,而 EclipseLinks 的默认 Moxy Json Provider 无法序列化此类 POJO。

您需要 Jackson Json Provider 而不是修改您的模型 Pojo 类。

我假设您正在使用 JaxRs REST api 尝试序列化 Pojos。在这种情况下,您可以很容易地使用来自 maven 的 Jackson 包。只需为 jaxb 提供者和对象映射器创建提供者。更多细节可以在这里找到:

https://stackoverflow.com/a/60319306/5076414

您需要 JSOG 库和提供者:https://github.com/jsog/jsog-jackson

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多