# 실전 예제 2 - 연관관계 매핑 시작

이전과 테이블은 동일한데 **참조를 사용하도록 변경**한다! 좀 더 객체지향적으로!

![테이블 설계](https://1863485745-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MeTGDBevaFvc3bwqqht%2F-MehodygwlB0vG89mIvN%2F-MehoyIz6Nc-3HJOZN7e%2F%E1%84%89%E1%85%B5%E1%86%AF%E1%84%8B%E1%85%A82%20%E1%84%90%E1%85%A6%E1%84%8B%E1%85%B5%E1%84%87%E1%85%B3%E1%86%AF%E1%84%8B%E1%85%A7%E1%86%AB%E1%84%80%E1%85%AA%E3%85%97%E3%84%B4%E1%84%80%E1%85%AA%E1%86%AB%E1%84%80%E1%85%A8.png?alt=media\&token=b7743e68-0fdd-424b-8731-fa169eb8889a)

![객체 연관관계](https://1863485745-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MeTGDBevaFvc3bwqqht%2F-MehodygwlB0vG89mIvN%2F-Mehp3AZ7wcpS49Pm-NO%2F%E1%84%89%E1%85%B5%E1%86%AF%E1%84%8B%E1%85%A82%20%E1%84%80%E1%85%A2%E1%86%A8%E1%84%8E%E1%85%A6%20%E1%84%80%E1%85%AE%E1%84%8C%E1%85%A9.png?alt=media\&token=512f38be-7618-4b1a-9ee3-6ec33c2fb29b)

양방향 관계 설계\
가급적이면 단방향으로 설계하고, 필요에 따라 참조관계 추가한다!\
FK가 있는 쪽을 주인으로 한다!\
단방향으로 FK 잘 매핑해주도록 한다!\
양방향이 필요하면 그때 필요한 필드 객체(참조값)를 추가한다!

비즈니스 흐름을 살펴봤을 때, 주문->주문상품->상품으로 조회하는데\
그 역방향으로 상품->주문상품->주문 순으로 조회하는 않는다.

ex) 주문서들을 보고 상품을 찾는다.\
&#x20;     상품을 보고 주문서들을 찾는다.❌

특정 회원의 주문 내역을 조회할 때 굳이 MEMBER 테이블의 Orders 컬렉션을 조회하는 것보다 ORDERS 테이블의 MEMBER\_ID(FK) 조회하면 가능하다.\
(예시라서 한것일 뿐. 잘못된 코드라고 할 수 있다. 없는 것이 비즈니스 로직 흐름에도 더 적합)

FK로 단방향 관계 매핑까지하고 나서 필요에 따라 연관관계 역방향으로도(양방향) 만들어준다.\
\=>Order 엔티티에서 바로 orderItems 컬렉션에 접근하고 싶을 때!

사실 ORDERS의 orderItems(List)도, MEMBER의 orders(List)도 없어도 문제 없다.\
연관관계 매핑에 문제가 없다. \
양방향 관계가 아니어도 애플리케이션 개발에 아무런 문제가 없다.\
\=>조회를 좀 더 편하게 하고, JPQL을 편하게 작성하려하다 보면 양방향 관계가 나오게 된다.

코드로 이해:\
다음의 코드처럼 Order, OrderItem 객체를 각각 생성해서 setter로 참조관계를 넣어주면 된다.

```
Order order = new Order();
em.persist(order);

OrderItem orderItem = new OrderItem();
orderItem.setOrder(order);
em.persist(order);
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://heunnajo.gitbook.io/jpa-basic/5./2-1.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
