JAX-RS JSON serialization loop with JPA entities JAX-RS JSON serialization loop with JPA entities json json

JAX-RS JSON serialization loop with JPA entities


Modify your Playlist entity class:

@Entity@JsonIgnoreProperties({"owner"})public class Playlist {

Your Jackson is running to recurency when he tries to serialize User which have Playlist which have User and so on...


Find the @MGorgon answer useful.

In my case I want to use hibernate along with jersey but retrieve only id of relation (and not loading the entire object) in a RestFull json web service.

I end up creating a field for the id:

@JsonIgnoreProperties({"parent"}) // this ignores the object for json serializationpublic class Object{  private int id;  private AnotherObj parent;  @Transient // this ignores the properties for hibernate mapping, cause we want to use the parent.getId() instead. You may have to put it in your get too  private ind parent_id;}

Then in your ObjectDao query you can define the parent id as parent_id if you need to get it from a relation :

something like "from files WHERE user_id = parent_id").

You will have to do this for all your queries:

  Object.setParent_id(Object.getParent().getId());

Because parent_id is transient, invisible to hibernate and it wont be listed otherwise.

And of course you should use LAZY relations (otherwise it would load the obj anyway). It works because the parent_id is a column of the object table, it wont need to make a call to parent.

This is useful when you have a lot of relations but you just need to query the id.