EclipseLink MOXy,在对象图中循环

时间:2013-12-09 14:34:21

标签: java eclipselink moxy

有没有办法编组/解组以下User-Entity-Object? 一些特殊的注释?

抽象类中的用户是编辑User-Entity-Object的用户。 这两个用户完全相同。 执行以下代码将引发以下异常:

org.eclipse.persistence.exceptions.XMLMarshalException Exception Description: A cycle is detected in the object graph

import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlRootElement;
import org.eclipse.persistence.jaxb.JAXBContextFactory;
import org.eclipse.persistence.jaxb.MarshallerProperties;
import org.eclipse.persistence.oxm.MediaType;

public class UserApp {

  public static abstract class AbstractEntity {

    private Long id;

    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

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

    public Long getId() {
        return id;
    }
  }

  @XmlRootElement
  public static class User extends AbstractEntity {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
  }

  public static void main(String[] args) throws JAXBException {
    UserApp userApp = new UserApp();
    User user = new User();
    user.setId(1L);
    user.setName("Jim");
    user.setUser(user);

    String marshalledUser = userApp.marshal(user);
    System.out.println(marshalledUser);
    User unmarshalledUser = userApp.unmarshal(User.class, new StringReader(marshalledUser));
  }

  private String marshal(Object toMarshal) throws JAXBException {
    JAXBContext jc = JAXBContextFactory.createContext(new Class[] {toMarshal.getClass()}, null);
    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON);
    StringWriter sw = new StringWriter();
    marshaller.marshal(toMarshal, sw);
    return sw.toString();
  }

  private <T> T unmarshal(Class<T> entityClass, StringReader sr) throws JAXBException {
    JAXBContext jc = JAXBContextFactory.createContext(new Class[] {entityClass}, null);
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    unmarshaller.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON);
    return (T) unmarshaller.unmarshal(sr);
  }
}

1 个答案:

答案 0 :(得分:1)

目前,MOXy不支持映射双向关系,其中两个方向都使用相同的属性。您可以使用以下链接跟踪我们在此问题上的进展: