Spring Data JPA @OneToOne annotation Infinite Recursion Error

前端 未结 2 505
天命终不由人
天命终不由人 2021-01-14 10:42

Husband.java

package com.example.demo.com.example.domain;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstruc         


        
2条回答
  •  再見小時候
    2021-01-14 11:08

    This is a known issue, when you have bidirectional relation jackson will try to serialize each reference of one side from the other side so its logical to have infinite recursion.

    Solution: There are many solutions to that , you could use @JsonIgnore on one side to avoid serializing the annotated reference hence breaking the infinite recursion

     @EqualsAndHashCode(exclude = "husband",callSuper = false)
     @Entity
    @Table(name = "t_wife")
    public class Wife {
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    private String name;
    
    @OneToOne(mappedBy = "wife",cascade = {CascadeType.ALL})
    @JsonIgnore
    private Husband husband;
    
    //omitted getter/setter
    }
    

    you also could use @JsonManagedReference/@JsonBackReference, check this link for more info how to use them

    This answer has one problem , if you try to serialize wife direction you will not have husband object since the solution was to avoid serializing it.

    There is a nice solution to this, its mentioned in this link , the idea is to generate a reference to the parent entity, so if you are serializing husband, you will have husband->wife->[reference to husband instead of husband], all you need to do is to annotate your entities with @JsonIdentityInfo

    @EqualsAndHashCode(exclude = "husband",callSuper = false)
    @Entity
    @Table(name = "t_wife")
    @JsonIdentityInfo(generator=ObjectIdGenerators.UUIDGenerator.class, property="@id")
    public class Wife {
    
    @JsonIdentityInfo(generator=ObjectIdGenerators.UUIDGenerator.class, property="@id")
    @Entity
    @Table(name = "t_husban")
    public class Husband {
    @Id
    

提交回复
热议问题