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

后端 未结 9 737
天涯浪人
天涯浪人 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:10

    I got the main problem of this situation.

    When you get Movie, system will load a list of relation Clips, but in CLip class you have a property Movie, when you have getter of this property, system will load Movie again.

    Movie.java
        @OneToMany(mappedBy = "movie", targetEntity = Clip.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
        private Set clips = new HashSet();
    
    //the below getter will look for data of related Clip
        public Set getClips(){ return this.clips}
    
    
     Clip.java
    
        @ManyToOne
            @JoinColumn(name="movie_id")
            private Movie movie;
    
    //the below getter will look for related Movie again
       public Movie getMovie() { return this.movie }
    
    

    For example: You get Movie 01, this movie has relation with Clip 01 and Clip 02, when system load data of Movie 01 it also fetch data of Clip 01 and Clip 02 via your getter method.

    But in Clip class you also has property Movie and a getter getMovie(). So when system looks for data of CLip 01, it also get data of relation Movie, in this situation is Movie 01... and Movie 01 will get data of CLip 01 => So this is exactly reason why we have a loop

    So that the exactly solution for this situation is Delete Getter Method getMovie() in Clip.java we dont need to use this information

提交回复
热议问题