Spring JPA λ₯Ό 곡λΆνλ μ€ μλ°©ν₯ κ΄κ³μ μλ Entity μ€ νλλ₯Ό λΆλ¬μ€λ κ³Όμ μμ μλμ κ°μ μ€λ₯κ° λ°μνμ¬μ ν΄κ²°νλ κ³Όμ μ μ 리ν΄λ³΄μλ€.
Could not write JSON: Infinite recursion ...
μ뱑ν₯ κ΄κ³μ μλ Entity λ Question κ³Ό Answer μλλ° μλμ κ°μ ꡬ쑰 μλ€.
@Entity
public class Question { // λΆλͺ¨ μν°ν°
// (μλ΅)
@OneToMany (mappedBy = "question", cascade = {CascadeType.REMOVE, CascadeType.PERSIST})
private List<Answer> answerList = new ArrayList<>();
}
@Entity
public class Answer { // μμ μν°ν°
// (μλ΅)
@ManyToOne
private Question question;
}
1οΈβ£ @JsonIgnore μ¬μ©
ν΄λΉ μ΄λ Έν μ΄μ μ΄ λΆμ Entity λ μμ null μ²λ¦¬ νμ¬ λ°μ΄ν°μ μμ ν¬ν¨μν€μ§ μλ λ°©μ.
- μ μ©
@Entity
public class Question { // λΆλͺ¨ μν°ν°
// (μλ΅)
@OneToMany (mappedBy = "question", cascade = {CascadeType.REMOVE, CascadeType.PERSIST})
@JsonIgnore // μΆκ°
private List<Answer> answerList = new ArrayList<>();
}

μ뱑ν₯ κ΄κ³μλ answerList λ null λ‘ μ·¨κΈλμ΄ μμ μ λ¬λλ λ°μ΄ν°μμ μμ λλ€. νμ§λ§ Question μ ν΅ν΄ answerList λ₯Ό λΆλ¬μμΌνλ μν©μ΄λΌλ©΄ μ΄ ν΄κ²°λ°©λ²μ λΆμ μ ν κ² κ°λ€.
2οΈβ£ @JsonManagedReference & @JsonBackReference μ¬μ©
λΆλͺ¨ μν°ν°μ @JsonManagedReference, μμ μν°ν°μ @JsonBackReference μ΄λ Έν μ΄μ μ μΆκ°νμ¬ κ΄κ³λ₯Ό λͺ νν ν΄μ£Όλ λ°©μ
- μ μ©
@Entity
public class Question { // λΆλͺ¨ μν°ν°
// (μλ΅)
@OneToMany (mappedBy = "question", cascade = {CascadeType.REMOVE, CascadeType.PERSIST})
@JsonManagedReference // μΆκ°
private List<Answer> answerList = new ArrayList<>();
}
@Entity
public class Answer { // μμ μν°ν°
// (μλ΅)
@ManyToOne
@JsonBackReference // μΆκ°
private Question question;
}

λ°©λ² 1οΈβ£ κ³Όλ λ€λ₯΄κ² answerList κΉμ§ λͺ¨λ λΆλ¬μ€λ κ²μ λ³Ό μ μλ€.
3οΈβ£ DTO ννλ‘ λ³ννμ¬ μ¬μ©
μ¬μ€ μ΄λ¬λ μ λ¬λ Entity λ₯Ό μ§μ μ λ¬νλ κ²μ μ¬λ¬ λΆλΆμμ λ³λ‘μ΄κΈ° λλ¬Έμ κ°λ₯νλ©΄ DTO λ₯Ό μμ±ν΄μ μ¬μ©νλ κ²μ΄ μ’λ€. DTO λ₯Ό μμ±νμ¬ λ°μ΄ν°λ₯Ό μ λ¬νλ λ°©μμ μλ κΈμ μμΈν μ 리ν΄λμλ€.
https://like099.tistory.com/29
(Spring) Entity μμ DTO λ³ν ν μ¬μ©
π 곡λΆνκ² λ κ³κΈ° λ§€λ² Entity μ DTO μ μ°¨μ΄μ μ¬μ©λ²μ λν΄ ν·κ°λ¦¬κ³ , μ νμνμ§μ λν΄ μκ°νλ μ μ΄ λ§λ€. νλ‘μ νΈμμλ λ€λ₯Έ νμ λΆλ€μ DTO λ₯Ό μμ λ‘κ² μ°μλλ° κ·Έλ μ§ λͺ»ν λ
like099.tistory.com
κ²°κ³Όλ§ μ μ΄λ³΄λ©΄ μλμ κ°μ΄ μ λ¬ν μ μλ€.

μ μ΄μ μν μ°Έμ‘° λ¬Έμ λ₯Ό λ°μμν€μ§ μμ λΏλλ¬ νμν λ°μ΄ν°λ§ ν¨μ¨μ μΌλ‘ κ°μ§κ³ μ¬ μ μμΌλ―λ‘ λ§μ§λ§ λ°©λ²μΈ DTO μ¬μ©μ μΆμ²νλ€.
'μ€λ΅λ ΈνΈ π' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
| (Spring JPA) UnsatisfiedDependencyException μλ¬ ν΄κ²° (0) | 2022.10.26 |
|---|---|
| (h2 DB) H2 DB μ€μ μ΄κΈ°ν νλλ² (0) | 2022.10.07 |