본문 바로가기

컴퓨터공학/Hibernate

Hibernate> @OneToOne, OneToMany, ManyToMany 복습

@OneToOne

 

 

uni directional mapping 
a가 b 테이블을 참조하는 상황에서
b테이블에서 a테이블 정보를 갖고오고 싶을 때
uni directional 관계는 그럴 수 없다. 
bi directional 관계는 가능
데이터 베이스 테이블에서 바꿀 것은 없다.
자바 코드에서 수정하면 된다. 

 

 

uni directional

참조하는 테이블의 id가 아니라 외래키 칼럼을 넣는다

 

bi directional

 

mapedBy 의 내용값의 의미는 Instructor 클래스에 있는 InstructorDetail 클래스 필드값이다. 

즉, 하이버네이트에게 말하고 있는 건

Instructor 클래스에 있는 instructorDetail 필드를 봐라

instructorDetail 필드에 JoinColumn을 정보를 봐라

알려주고 있다.

 

 

삭제할 때 한 쪽만 삭제하게 만들고 싶다면

cascade 조건에서 remove만 빼주고 나머지는 넣어준다. 

즉 이렇게 설정하면 삭제를 제외한 나머지는 연동이 된다. 

 

 

둘 다 삭제되면 문제 없는데 하나만 삭제하고 싶은 경우

두 테이블이 양방향이면 instrutor에서 instructor_detail을 참조하지 않게 끊어줘야 한다.

그래야 detail에서 삭제 가능

따라서 먼저 instructor에서 instructor_detail 로 연결하는 선을 끊어준다.

연결 선을 끊어주는 방법은 instructor에서 setInstructorDetail을 null 로 설정하면 된다.

그 다음에 instructor_detail을 삭제하면 정상적으로 instructor_detail이 삭제

 

 


@OneToMany

 

강의 정보가 지워진다고 학생 정보가 지워지진 않는다.

학생 정보를 지운다고 강의 정보가 없어지진 않는다.

cascade 조건 중에서 삭제는 걸지 말자

 

 

bi directional

이전에 bi directional 관계인 instructor 와 instructor_detail에서 cascade.remove를 설정하지 않았을 경우

instructor_detail을 삭제할 때 instructor에서 instructor_detail 로 연결되는 선을 끊은 다음 instructor_detail을 삭제했다. 

하지만 instructor와 course 연결 관계에서 course를 삭제할 때는 instructor에서 course로 연결되는 선을 끊지 않아도 된다. 그 이유는 foreign key 관계 때문이다.

course가 instructor를 참조하고 있기 때문에 course를 삭제하면 반대 방향인 instructor에서 course의 연결은 자동으로 사라진다.

bi directional 관계에서 foreign key 관계가 더 비중있다는 것을 알 수 있다. 

 

 

 

uni directional

왼쪽 그림을 보면 @JoinColumn 의 위치가 지금까지와 다르다. 

보통  JoinColumn은 foreign key 컬럼이 있는 클래스에 썼다. 

하지만 지금은 여러 리뷰를 갖고 있는 coruse에 JoinColumn이 있다.

왜냐하면 JoinColumn은 쓰는 환경에 따라서 다르다.

 

1. OneToOne이나 ManyToOne 상황에서 JoinColumn foreign key 은 쏘는 쪽에 있다.

2. unidirectional OneToMany 상황에서 JoinColumn foreign key 은 당하는 쪽에 있다.

3. ManyToMany 나 OneToOne 나 bidirectional ManyToOne/OneToMany 상황에서 JoinColumn foreign key 은 쏘는 쪽에 있다.

4. collection element 상황에서 JoinColumn foreign key 은 collection table에 있다.

JoinColumn (Java(TM) EE 7 Specification APIs) (oracle.com)

 

JoinColumn (Java(TM) EE 7 Specification APIs)

(Optional) The name of the foreign key column. The table in which it is found depends upon the context. If the join is for a OneToOne or ManyToOne mapping using a foreign key mapping strategy, the foreign key column is in the table of the source entity or

docs.oracle.com

 

이걸 따라서 보면

course는 여러 review를 uni directional 관계로 갖고 있고

one to many reviews이다.

그래서 join column foreign key 칼럼은 목표물이자 당하는 쪽에 있어야 하므로 

review에 있어야 한다.


@ManyToMany

위 클래스에서 아래 사진처럼 추가한다.