0

I'm about to design my rest API. I wonder how can I handle objects such as one below:

@Entity
public class Foo {
@ManyToMany
private Set<Bar> barSet;
@OneToMany
private Set<Zzz> zzzSet;
}

As you see object I want to expose to my rest API consists of other entity collections. I'm using Spring 4 and Jackson. Is it possible to return objects like one above - or do I have to create classes with primitive values only?

3
  • You can easily return objects like foo, but then you need to ignore the reference to foo in you bar class, otherwise jackson will crash. Commented Feb 22, 2016 at 14:21
  • Great. Could you tell me how to achieve this? Commented Feb 22, 2016 at 14:28
  • Use the @JsonIgnore annotation and annotate the reference of foo in the bar class. This will prevent you from getting a circular dependencie. Commented Feb 22, 2016 at 14:30

1 Answer 1

3

Yes, it is possible but you have to handle 2 problems :

1) at serialization, Jackson will call the getter Foo.getBarSet(). This will crash because by default, Hibernate returns lazy collections for @OneToMany and @ManyToMany relationships.

If you don't need them, annotate them with @JsonIgnore :

@Entity
public class Foo {

  @JsonIgnore
  @ManyToMany
  private Set<Bar> barSet;

  @JsonIgnore
  @OneToMany
  private Set<Zzz> zzzSet;
}

If you need them, you must tell hibernate to load them. For example, you can annotate @ManyToMany and @OneToMany with fetch = FetchType.EAGER (It is not the only solution btw) :

@Entity
public class Foo {

  @ManyToMany(fetch = FetchType.EAGER)
  private Set<Bar> barSet;

  @OneToMany(fetch = FetchType.EAGER)
  private Set<Zzz> zzzSet;
}

2) It can also cause some infinite loops :

  • Serialization of Foo calls Foo.getBarSet()
  • Serialization of Bar calls Bar.getFoo()
  • Serialization of Foo calls Foo.getBarSet()
  • [...]

This can be handled with @JsonManagedReference and @JsonBackReference :

@Entity
public class Foo {

  @JsonManagedReference
  @OneToMany
  private Set<Zzz> zzzSet;

And on the other side :

@Entity
public class Zzz {

  @JsonBackReference
  private Foo parent;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.