Spring Boot JPA one to many (단방향)

By | 2022년 9월 2일
Table of Contents

Spring Boot JPA one to many (단방향)

한 사람이 핸드폰을 여러개 가지고 있는 경우가 있다.

이 경우, 방향성은 사람->핸드폰 과 같이 단방향(unidirectional)이 된다.

이 경우 @OneToMany 를 이용해 관계를 설정해 준다.

속성

@OneToMany 에는 아래와 같은 속성이 있다.

targetEntity

이름 그대로 대상 Entity 이다.

cascade

한 Entity 의 변경이 다른 Entity 에 어떻게 반영하느냐의 방식이다.

CascadeType라는 enum에 정의 되어 있으며,
ALL, PERSIST, MERGE, REMOVE, REFRESH, DETACH 등이 있다.

fetch

관련 Entity 에 대한 읽기 전략이다.

FetchType.EAGER : 즉시 읽기
FetchType.LAZY : 지연 읽기(요청이 있을 때 읽기)

mappedBy

양방향일때만 사용

orphanRemoval

DB 수준의 cascade

예제

상품정보->상품추가이미지정보 의 단방향 연결 상태입니다.

@Entity
public class SrcItemEntity {
    @Id
    @Column(name = "itemid", nullable = false)
    private Integer id;

    @OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL)
    @JoinColumn(name="itemid")
    private List<SrcItemAddImageEntity> addImage;

    // ......
}

현재 Entity 의 @Id 와 SrcItemAddImageEntity 의 itemid 필드를 연결하게 됩니다.

@Entity
public class SrcItemAddImageEntity {

    @Id
    @Column(name = "idx", nullable = false)
    private Integer id;

    private Integer itemid;

    // ......
}

위 설정만으로 관련 Entity 가 읽어집니다.

성능이슈??

원래 Entity 의 갯수만큼 연관 Entity 에 대한 쿼리가 실행됩니다.

성능은 좋을지…

답글 남기기