Frage

is there a way to marshal/unmarshal the following User-Entity-Object? Some special annotation?

The User in the abstract class is the user who edited the User-Entity-Object. Its perfectly legal that these both users are identical. Executing the following code will throw the following exception:

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);
  }
}
War es hilfreich?

Lösung

Currently MOXy doesn't support mapping a bidirectional relationship where both directions use the same property. You can use the link below to track our progress on this issue:

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top