학생이 수강신청을 하는 DB를 예시로 들어보겠다.

 

한 명의 student는 여러 개의 lecture에 들어갈 수 있고 

마찬가지로 하나의 lecture에도 여러 student가 포함될 수 있는 N:N관계의 DB다.

위와 같이 N : N 관계의 테이블 설정에서는 @ManyToMany 를 아래와 같이 설정할 수 있다.

 

@Entity
@Getter @Setter
public class Student {

    @Id
    @Column(name = "student_id")
    private Long id;

    private String name;

    @ManyToMany
    @JoinTable(name = "student_lecture"
            ,joinColumns = @JoinColumn(name = "student_id")
            ,inverseJoinColumns = @JoinColumn(name = "lecture_id"))
    private List<Lecture> lectures = new ArrayList<>();
}

 

@Entity
@Getter @Setter
public class Lecture {
    @Id
    @Column(name = "lecture_id")
    private Long id;

    @ManyToMany(mappedBy = "lectures")
    private List<Student> students = new ArrayList<>();
}

 

 

하지만 문제는 실제 테이블을 작성하다보면

student_lecture 테이블에 create_time, update_time 등의 다른 칼럼들이 추가될 일은 많은데

@ManyToMany로 Entity의 변수를 매핑하다 보면 student_lecture 테이블에 다른 column을 추가할 방법이 없다는 것이다.

 

그러한 이유로 아래와 같이 별도의 StudentLecture 클래스를 두고 @OneToMany , @ManyToOne을 사용하여 매핑하는 것을 추천한다.

@Entity
@Getter @Setter
public class Student {

    @Id
    @Column(name = "student_id")
    private Long id;

    private String name;

    @OneToMany(mappedBy = "student")
    private List<StudentLecture> studentLectures = new ArrayList<>();
}
@Entity
@Getter @Setter
public class Lecture {
    @Id
    @Column(name = "lecture_id")
    private Long id;

    @OneToMany(mappedBy = "lecture")
    private List<StudentLecture> studentLectures = new ArrayList<>();
}
@Entity
@Getter @Setter
public class StudentLecture {

    @Id
    @Column(name = "student_lecture_id")
    private Long id;

    @ManyToOne
    @JoinColumn(name = "student_id")
    private Student student;

    @ManyToOne
    @JoinColumn(name = "lecture_id")
    private Lecture lecture;
    
    private LocalDateTime createTime;
    private LocalDateTime updateTime;
}

위와 같이 @ManyToMany 대신 @OneToMany, @ManyToOne 을 사용하고

다대다 관계를 매핑할수 있는 클래스를 사용하면 column을 추가하는 것이 가능해진다.

 

 

틀린 부분은 지적해주시면 언제나 감사히 수정반영 하겠습니다.😄

+ Recent posts