Board.java
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity
public class Board {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY) // auto_increment
private int id;
@Column(nullable = false, length = 100)
private String title;
@Lob
private String content;
private int count;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name="userId")
private User user;
@OneToMany(mappedBy = "board", fetch = FetchType.EAGER)
private List<Reply> replys;
@CreationTimestamp
private Timestamp createDate;
}
Reply.java
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Data
@Entity
public class Reply {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(nullable = false, length = 200)
private String content;
@ManyToOne
@JoinColumn(name = "boardId")
private Board board;
@ManyToOne(fetch = FetchType.EAGER
@JoinColumn(name="userId")
private User user;
@CreationTimestamp
private Timestamp createDate;
}
ReplyControllerTest
@RestController
public class ReplyControllerTest {
@Autowired
private BoardRepository boardRepository;
@GetMapping("/test/board/{id}")
public Board getBoard(@PathVariable int id) {
return boardRepository.findById(id).get(); // jackson 라이브러리 (오브젝트를 json으로 리턴) => 모델의 getter를 호출
}
}
http://localhost:8001/test/board/1
Board 객체가 reply객체를 갖고 있고 reply객체는 Board객체를 갖고 있다.
즉 Board와 Reply를 계속 왔다갔다 하면서 무한 참조가 발생한다.
Board.java
@JsonIgnoreProperties 어노테이션을 Board에 추가해서 Board객체를 불러올때 Reply에 대해 참조를 막아서 무한참조를 방지한다.
@JsonIgnoreProperties({"board"}) // 참조 방지
@OneToMany(mappedBy = "board", fetch = FetchType.EAGER)
private List<Reply> replys;