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

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

    Easy way as Dino Tw said:

    Remove the getMovie() function from the Clip class.

    That will help you to retrieve the Clip list for each Movie which is associated by movie_id in the Clip entity/table.

    0 讨论(0)
  • 2020-12-06 05:32

    Basically JsonIgnore or JsonBackrefrencing will remove linking from one end.

    To make proper linking as well as correct Json output, please follow below code snippet :-

    @Entity  
    @Table(name="Movie")
    public class Movie{
    
    @JsonIdentityInfo(generator=ObjectIdGenerators.UUIDGenerator.class, property="@id")
    @OneToMany(mappedBy="movie",cascade=CascadeType.ALL,fetch=FetchType.EAGER)
    private Set<Clip> clips = new HashSet<Clip>();
    
    }
    
    
    @Entity  
    @Table(name="Clip")
    public class Clip{ 
    
    @JsonIdentityInfo(generator=ObjectIdGenerators.UUIDGenerator.class, property="@id")  
    @ManyToOne
    @JoinColumn(name="movie_id")
    @JsonIgnore
    private Movie movie;
    }
    

    refer below link for further details :- https://www.toptal.com/javascript/bidirectional-relationship-in-json

    import com.fasterxml.jackson.annotation.ObjectIdGenerators;
    
    0 讨论(0)
  • 2020-12-06 05:34

    Instead of returning an Entity object, I suggest return a DTO object only with the data you need. You can get one directly from a Hibernate query/criteria results, using result transformers.

    0 讨论(0)
提交回复
热议问题