연관관계에 들어가기 전에 간단한 키워드들이 있어 정리하고 들어가보려 한다.
객체 연관관계와 테이블 연관관계 차이
public class Student {
...
@ManyToOne
@JoinColumn(name = "SCHOOL_ID")
private School school;
Tip. 단방향 관계를 매핑할 때 다대일/일대다 선택 기준은 반대편 관계에 달려 있다. 반대편이 일대다면 다대일, 반대편이 다대일이면 일대다를 사용하면 된다.
@Entity
public class School {
...
@OneToMany(mappedBy = "school")
List<Student> students = new ArrayList<Student>();
...
양방향 연관관계 매핑 시, 둘 중 하나를 주인으로 정해야한다. 이 주인만이 db 연관관계와 매핑되고 외래 키를 관리할 수 있다. 반대편은 오직 읽기만 할 수 있다.
따라서 읽기만 가능한 곳은 mappedBy 속성을 사용하여 주인 필드를 지정한 뒤 본인 필드는 읽기 전용이라고 명시해주어햐 한다.
public class Student {
...
@ManyToOne
@JoinColumn(name = "SCHOOL_ID")
private School school;
School과 Student간의 다대일 관계 매핑 예시
public class Student {
...
@ManyToOne
@JoinColumn(name = "SCHOOL_ID")
private School school;
...
public void setSchool(School school){
this.school = school;
if(!school.getStudents().contains(this)){
school.getStudents().add(this);
}
}
@Entity
public class School {
...
@OneToMany(mappedBy = "school")
private List<Student> students = new ArrayList<Student>();
...
public void addStudent(Student student){
this.students.add(student);
if (student.getSchool() != this){
student.setSchool(this);
}
}
...
@Entity
public class School {
...
@OneToMany
@JoinColumn(name = "SCHOOL_ID")
private List<Student> students = new ArrayList<Student>();
...
School과 Student간의 일대다 관계 매핑 예시
@Entity
public class School {
...
@OneToMany
@JoinColumn(name = "SCHOOL_ID")
private List<Student> students = new ArrayList<Student>();
...
public class Student {
...
@ManyToOne
@JoinColumn(name = "SCHOOL_ID", insertable = false, updatable = false)
private School school;
...
School과 Student간의 일대일 관계 매핑 예시
public class Student {
...
@OneToOne
@JoinColumn(name = "SCHOOL_ID")
private School school;
...
@Entity
public class School {
...
@OneToOne(mappedBy = "school")
private Student student;
...
School과 Student간의 다대다 관계 매핑 예시
public class Student {
...
@ManyToMany
@JoinTable(name = "STUDENT_SCHOOL",
joinColumns = @JoinColumn(name = "STUDENT_ID"),
inverseJoinColumns = @JoinColumn(name = "SCHOOL_ID"))
private List<School> schools = new ArrayList<School>();
...
@Entity
public class School {
...
@ManyToMany(mappedBy = "schools")
private List<Student> students;
...
I found my dream girl with this Delhi Escorts agency. She was warm, elegant, and incredibly sexy. The booking process was easy, and the experience was flawless. Trust this Delhi Escorts Agency for high-quality services and a night you'll remember forever. I’ve never been more satisfied.