Jaqen K'uba
Jaqen K'uba

Reputation: 289

REST API - nested objects

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?

Upvotes: 0

Views: 715

Answers (1)

Arnaud Denoyelle
Arnaud Denoyelle

Reputation: 31283

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;
}

Upvotes: 3

Related Questions