Hibernate @OneToMany Relationship Causes Infinite Loop Or Empty Entries in JSON Result

Solution:

Use

@JsonManagedReference annotation for the first objects instantiated

@JsonBackReference annotation for the second objects instantiated

Movie.java

@JsonManagedReference
@OneToMany(mappedBy = "movie", targetEntity = Clip.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private Set<Clip> clips = new HashSet<Clip>();

Clip.java

@JsonBackReference
@ManyToOne
    @JoinColumn(name="movie_id")
    private Movie movie;

I ran into exactly the same problem. I tried the solution from the quoted paragraph, it did not work for me.

What I did is to return null for getMovie() in Clip class, then the infinite loop issue is gone. The data returned in JSON format will look like {"movieId":1 ... clips:["clipId":1, "movie":"null", ..]}.

If you also want further remove the movie property in JSON, add the class-level annotation to Clip class @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)

Jackson feature: prevent serialization of nulls, default values

Update: The easier way I found is to simply remove the getter of movie in Clip class.


First, let me show you why setting fetch type to lazy doesn't help. When you try to serialize your pojo, your serializer (maybe jackson) would call every getter of this pojo, and use the returned value of getter as the properties in json data. So it calls the getter explicitly, which calls hibernate to load your associated entities ( movie for Clip and clips for Movie ). So you need to use @JsonIgnoreProperties to get rid of this weird infinite loop, the code goes like this:

Clip.java

    @ManyToOne
    @JoinColumn(name="movie_id")
    @JsonIgnoreProperties("clips")
    private Movie movie;

Movie.java
    @OneToMany(mappedBy = "movie", targetEntity = Clip.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JsonIgnoreProperties("movie")
    private Set<Clip> clips = new HashSet<Clip>();

That way, you would find the nested movie in clip json object has no "clips" inside movie, and the nested clips in movie has no "movie" child neither.

I guess this is the best way to deal with this problem, and also the best practice to develop java web app.