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

后端 未结 9 744
天涯浪人
天涯浪人 2020-12-06 05:07

I have two entities, an entity \"movie\" and an entity \"Clip\" each clip belongs to one movie and a movie can have multiple clips.

My code looks like:



        
9条回答
  •  余生分开走
    2020-12-06 05:11

    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 clips = new HashSet();
    

    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.

提交回复
热议问题