대외활동 기록/NEXTERS 15th

[JPA] OneToMany, ManyToMany 관계 설정하기

칸타탓 2019. 7. 28. 16:40

OneToMany, 단방향(unidirectional relationships)

Entity간의 관계를 맺을 때에는 방향이 있다. 방향이라 하는 것은 해당 Entity가 다른 Entity를 가질 수 있는지 이다.

유저 Entity에서 책 Entity를 멤버 변수로 가지고 있다면 유저 -> 책이라는 방향성을 가진다.

이렇게 한쪽 방향만 가지는 것이 단방향(unidirectional)

 

책 Entity에서도 유저 Entity를 가진다면 유저 <-> 책 관계가 성립

=> 양방향(bidirectional) 관계

 

유저는 가지고 있는 책이 없거나 1개 이상을 소지할 수 있다. (1:N 관계)

JPA 어노테이션으로는 @OneToMany라고 표현

 

User.java

@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Getter
@Entity
public class User {
    @Id
    @Column
    @GeneratedValue
    private Long id;

    @Column(length=50, nullable= false)
    private String name;

    /* 한 명의 유저는 다수의 책을 가질 수 있다. */
    @OneToMany
    @JoinColumn(name="user_id")
    private Collection<Book> book;

    @Builder
    public User(String name) {
        this.name = name;
    }
}

Book.java

@NoArgsConstructor
@Getter
@Entity
public class Book{
    @Id
    @Column
    @GeneratedValue
    private Integer id;

    @Column(name="user_id")
    private Long userId;
    
    @Column
    private String title;

    @Column
    private LocalDateTime publisedAt;

    @Builder
    public Book(String title, LocalDateTime publishedAt){
        this.title = title;
        this.publisedAt = publishedAt;
    }
}

 

그리고 프로젝트를 실행시켜보면 아래와 같은 쿼리문이 실행된 것을 콘솔창을 통해 볼 수 있다.

 

user_id를 외래키로 가진다.

 

AnnotationException: Illegal attempt to map a non collection as a @OneToMany, @ManyToMany or @CollectionOfElements 라는 문제가 발생했는데, Collection을 사용해 타입을 매핑해주어 해결하였다.

 


[참고] https://jdm.kr/blog/141

 

'대외활동 기록 > NEXTERS 15th' 카테고리의 다른 글

[Spring] 자바 직렬화 Serializable (+JPA Entity)  (0) 2019.08.03
[JPA] SQL Mapper와 ORM  (0) 2019.07.28