본문 바로가기

Programming!

단일테이블의 Tree 구조를 위한 Self Join

Oracle의 tree 구조 start with/connect by 형태와 동일하게 구현하고자 할 경우, JPA도 Self Releastion으로 처리할 수 있다.


가령 ForumCategory Entity가 존재한다면 다음과 같이 처리된다.


public class ForumCategory {


    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Long id;


    @Where(clause = "deleted='N'")

    @ManyToOne(cascade = { CascadeType.ALL }, fetch = FetchType.LAZY)
    @JoinColumn(name = "parentId")
    private ForumCategory parent;

   

    @Where(clause = "deleted='N'")

    @OneToMany(fetch = FetchType.LAZY)
    @JoinColumn(name = "parentId")
    private List<ForumCategory> children = new ArrayList<ForumCategory>();


    @Column(name = "deleted", length = 1, nullable = false)
    private String deleted = "N";

.....

}



'could not initialize proxy - no Session'와 같은 오류 문구(transactional 유의)를 보게 된다. 조금만 찾아보면 이렇게 고쳐야 겠구나..하는 코드를 볼 수 있다.



lombok의 @Data나 @ToString 사용에 유의해야 한다.