Skizzo
Skizzo

Reputation: 2983

Trouble with my first RESTful Web Services

i'm developing my firts RestFul webServices in javaEE6. This is my Entity Bean

@XmlRootElement
@Entity
public class MyEntity implements Serializable {

 @Id
 @GeneratedValue
 private long idEntity;

 private String name;

 private String description;

 @OneToMany(mappedBy = "entity" , fetch = FetchType.EAGER)
 private List<EntityB>  list;

  //Get and set
}

 @Entity
 public class EntityB {

 @Id
 @GeneratedValue
 private long idCategoria;

 @ManyToOne
 private MyEntity myEntity;

  }

this is my webServices

@Path("myentity")
@Produces( {MediaType.APPLICATION_XML , MediaType.APPLICATION_JSON })
@Consumes( {MediaType.APPLICATION_XML , MediaType.APPLICATION_JSON })
@Stateless
public class MyEntityService {

 @Inject
 MyEntityDao entityDao;

 @GET
 @Path("{id}/")
 public MyEntity findById(@PathParam("id") Long id){
    return entityDao.findById(id);
 }
}

Finally i configured Jersey

@ApplicationPath("ws")
public class ApplicationConfig extends Application {

}

Now , if i try a invoke my web services (localhost:8080/xxxx/ws/myentity) i get this error:

HTTP Status 500 - javax.xml.bind.MarshalException - with linked exception: [com.sun.istack.SAXException2: A cycle is detected in the object graph. This will cause infinitely deep XML

Upvotes: 0

Views: 160

Answers (1)

Samuel EUSTACHI
Samuel EUSTACHI

Reputation: 3156

You have a cyclic Graph of objects, which is not allowed , as it would result in an "infinite" XML.

MyEntity Holds a reference to EntityB , which holds a reference that goes back to MyEntity.

The marshaller will try to marshall MyEntity > EntityB > MyEntity > EntityB and so on.

You can mark MyEntity in EntityB as @XmlTransient, to avoid this.

However, It might not be a good idea to try to use the same Classes of objects across all your project (From persistence layers to communication layers).

Upvotes: 2

Related Questions