2017-05-23 2 views
0

양방향 relationshop (일대 다, many to one)이있는 두 엔터티가있는 스프링 나머지 백엔드가 있습니다. 중첩 된 가져 오기 문제를 극복하기 위해 @ JsonManagedReference/@ JsonBackReference는 엔터티 간의 perent/child 관계에 사용되었습니다.양방향 최대 절전 매핑에서 MIssing 부모 참조

entites이 같은 모양 : 부모 요소를 가져 오는 경우에 잘 작동

@Entity 
@Table(name = "Parent") 
@JsonInclude(JsonInclude.Include.NON_NULL) 
public class Parent implements java.io.Serializable { 

    private Integer id; 
    private List<Child> childList; 

    @Id 
    @GeneratedValue(strategy = IDENTITY) 
    @Column(name = "ID", unique = true, nullable = false) 
    public Integer getId() { 
     return this.id; 
    } 
    public void setId(Integer id) { 
     this.id = id; 
    } 

    @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY) 
    @JsonManagedReference 
    public List<Child> getChildList() { 
     return childList; 
    } 

    public void setChildListe(List<Child> childListe) { 
      this.childList = childList; 
     } 

    } 


@Entity 
@Table(name = "Child") 
@JsonInclude(JsonInclude.Include.NON_NULL) 
public class Child implements java.io.Serializable { 


    private Integer id; 
    private Parent parent; 

    @Id 
    @GeneratedValue(strategy = IDENTITY) 
    @Column(name = "ID", unique = true, nullable = false) 
    public Integer getId() { 
     return this.id; 
    } 

    public void setId(Integer id) { 
     this.id = id; 
    } 

    @ManyToOne(fetch = FetchType.LAZY) 
    @JoinColumn(name = "ParentID") 
    @JsonBackReference 
    public Parent getParent() { 
     return parent; 
    } 

    public void setParent(Parent parent) { 
     this.parent = parent; 
    } 


} 

상기 childset 함께 다음 페치 및 JSON 배열로 표시된다.

그러나 jsonbackreferance를 사용하기 때문에 하위 요소에는 parent에 대한 참조가 없습니다. 어떻게이 문제를 해결할 수 있습니까? 자식을 가져올 때 부모 참조가 필요합니다.

답변

1

이렇게하면 JSON에 직렬화 할 때 무한 루프가 발생합니다. 그것이 양방향 JSON 관계를 수행하지 않는 이유입니다.

ID 만 필요할 경우 하위 엔터티에 추가 열을 추가하는 것입니다.

private Integer parentId; 

@Column(name = "ParentID", insertable=false, updateable=false) 
public Integer getParentId() { 
    return parentId; 
}