Thursday 19 January 2012

Ignore a parent class when Serializing to XML

Scenario: I use JPA and have create a Generic Entity entity which extend all the classes that I want to persist. Now I want some classes to be serialized into XML with JAXB. But I get an Exception because Serializable cannot be serialized into XML by JAXB. Code with error:
// "implements Serializable" gives Exception #1
public class GenericEntityImpl implements Serializable {

// gives Exception #2
protected PK id = null;
// gives Exception #3
protected Locale locale;

}
@XmlRootElement(name="child")
public class Child extends GenericEntityImpl {



}
Exception:
Caused by: com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 3 counts of IllegalAnnotationExceptions
java.io.Serializable is an interface, and JAXB can't handle interfaces.
 this problem is related to the following location:
  at java.io.Serializable
  at public java.io.Serializable core.domain.GenericEntityImpl.getId()
  at core.domain.GenericEntityImpl
  at foo.Child
java.io.Serializable does not have a no-arg default constructor.
 this problem is related to the following location:
  at java.io.Serializable
  at public java.io.Serializable core.domain.GenericEntityImpl.getId()
  at core.domain.GenericEntityImpl
  at foo.Child
java.util.Locale does not have a no-arg default constructor.
 this problem is related to the following location:
  at java.util.Locale
  at public java.util.Locale core.domain.GenericEntityImpl.getLocale()
  at core.domain.GenericEntityImpl
  at foo.Child
Code without error (recommendation link):
@XmlAccessorType(XmlAccessType.NONE)
public class GenericEntityImpl implements Serializable {

// same

}
@XmlRootElement(name="child")
public class Child extends GenericEntityImpl {

// same

}
Notes: Tried adding on GenericEntityImpl the annotation @XmlTransient but didn't work. Also tried adding to Child the annotation @XmlAccessorType(XmlAccessType.FIELD) and moving all the JAXB annotation on the attributes but didn't work either (see this recommendation); note that the JPA annotations are on the methods.

No comments:

Post a Comment