JPA 단방향 연관관계 매핑의 문제점과 해결 — @OneToMany 단방향은 왜 피하나
JPA에서 연관관계를 어느 방향으로 매핑하는지는 단순한 취향 문제가 아닙니다. 특히 @OneToMany 단방향은 멀쩡해 보여도 숨은 쿼리를 만들어, 저장할 때마다 불필요한 UPDATE가 나가거나 의도치 않은 조인 테이블이 생깁니다. 단방향 매핑의 문제를 살펴보고, 실무에서 사용하는 해결 방향을 정리합니다.
@OneToMany 쪽이 컬렉션을 주인처럼 관리하면, DB가 FK를 채우려고 추가 쿼리를 발생시킵니다.
"FK가 없는
@OneToMany쪽"이란?FK 컬럼(
member_id)은 다(N)쪽인orders테이블에만 있고,@OneToMany를 거는 일(1)쪽Member테이블에는 FK가 없습니다(member에는id만,orders에는id,member_id). 그 FK 없는Member가 컬렉션을 주인처럼 관리하면, 자기 것이 아닌orders.member_id를 원격으로 채우느라 추가 쿼리가 생깁니다 — 자세한 구조는 아래 "문제"에서 그림으로 봅니다.
연관관계 — "DB의 FK 하나를 누가 채우나"
먼저 방향은 객체(JPA) 쪽 개념입니다. 한쪽에서만 참조하면 단방향, 양쪽이 서로 참조하면 양방향입니다.
여기서 헷갈리기 쉬운 "연관관계의 주인"은 사실 단순합니다. DB에는 두 테이블을 연결하는 외래 키(FK) 컬럼이 딱 하나 — orders.member_id — 뿐입니다. 객체에서는 Member와 Order가 서로를 참조할 수 있지만, 저장할 때 이 유일한 FK 값을 실제로 채우는(INSERT/UPDATE) 쪽은 한 곳으로 정해야 합니다. 그 한 곳이 주인입니다.
- FK 컬럼(
member_id)은orders테이블에 있습니다 → 그 값은Order를 저장할 때 채워집니다 → 그래서 주인은Order.member. - 반대쪽
Member.orders는 읽기 전용입니다.mappedBy = "member"로 "FK 관리는Order.member가 하고, 이쪽은 조회만 한다"를 선언합니다.
member_id)을 가진 orders의 엔티티, 즉 Order가 주인이고, 주인만 FK를 채웁니다. 주인이 아닌 쪽(mappedBy인 Member.orders)에서 컬렉션을 수정해도 DB의 FK는 변하지 않습니다.
직관적으로는 "부모인
Member(일대다의 '1')가 주인"일 것 같지만, JPA의 주인은 FK를 가진 자식Order(일대다의 'N') 입니다 — 방향(부모, 자식)이 아니라 FK 위치로 정해집니다.
SVG 코드
<svg xmlns="http://www.w3.org/2000/svg" width="440" height="264" viewBox="0 0 440 264" font-family="-apple-system, 'Segoe UI', 'Noto Sans KR', sans-serif">
<defs><marker id="ah" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" fill="#888"/></marker></defs>
<rect x="0" y="0" width="440" height="264" fill="#FFFFFF"/>
<g transform="translate(0,-24)">
<rect x="16" y="40" width="190" height="64" rx="6" fill="#E9F2E9" stroke="#8FBF8F"/>
<text x="111.0" y="61.0" font-size="12" fill="#2E6B2E" text-anchor="middle" font-weight="bold">Order.member (주인)</text>
<text x="111.0" y="76.0" font-size="10.5" fill="#444" text-anchor="middle">@ManyToOne</text>
<text x="111.0" y="91.0" font-size="10.5" fill="#444" text-anchor="middle">+ @JoinColumn</text>
<rect x="234" y="40" width="190" height="64" rx="6" fill="#FFFBEA" stroke="#E0A000"/>
<text x="329.0" y="68.5" font-size="12" fill="#5A4300" text-anchor="middle" font-weight="bold">Member.orders (주인 아님)</text>
<text x="329.0" y="83.5" font-size="10.5" fill="#444" text-anchor="middle">@OneToMany(mappedBy)</text>
<rect x="130" y="206" width="180" height="64" rx="6" fill="#FCE4EC" stroke="#D06A86"/>
<text x="220.0" y="227.0" font-size="12" fill="#9E3A57" text-anchor="middle" font-weight="bold">orders 테이블</text>
<text x="220.0" y="242.0" font-size="10.5" fill="#444" text-anchor="middle">id | member_id</text>
<text x="220.0" y="257.0" font-size="10.5" fill="#444" text-anchor="middle">(FK는 하나)</text>
<line x1="111" y1="104" x2="180" y2="205" stroke="#888" stroke-width="1.2" marker-end="url(#ah)"/>
<text x="118" y="148" font-size="10.5" fill="#333" text-anchor="end">FK를 채움</text>
<text x="118" y="162" font-size="10.5" fill="#333" text-anchor="end">(INSERT/UPDATE)</text>
<line x1="329" y1="104" x2="260" y2="205" stroke="#888" stroke-width="1.2" stroke-dasharray="5 4" marker-end="url(#ah)"/>
<text x="322" y="148" font-size="10.5" fill="#333" text-anchor="start">조회만</text>
<text x="322" y="162" font-size="10.5" fill="#333" text-anchor="start">(FK 못 바꿈)</text>
</g>
</svg>
예시는 회원(Member) 1 : N 주문(Order) 입니다 — FK member_id는 orders 테이블에 있습니다.
@ManyToOne 단방향 — 기본이자 깔끔한 선택
FK를 가진 Order가 Member를 참조하는 다대일 단방향은 문제가 없습니다. 자식이 자기 FK를 직접 알고 있어, 저장이 INSERT 한 번으로 끝납니다.
@Entity
class Order {
@Id @GeneratedValue
Long id;
@ManyToOne(fetch = FetchType.LAZY) // 지연 로딩 기본 권장
@JoinColumn(name = "member_id") // orders.member_id (FK) = 연관관계 주인
Member member;
}
-- order를 저장하면 FK까지 한 번에
INSERT INTO orders (id, member_id) VALUES (?, ?);
다대일 단방향은 FK를 가진 쪽이 주인이라 자연스럽고, 대부분의 매핑은 이걸로 시작하면 됩니다. 한계는 한 가지입니다 — 부모(Member)에서 주문 목록으로 바로 탐색할 수 없다는 점입니다.
@OneToMany 단방향의 문제
반대로 부모 Member가 컬렉션으로 Order를 단방향 참조하면, FK는 orders에 있는데 그 FK를 Member 쪽에서 관리하게 됩니다. 여기서 두 가지 문제가 생깁니다.
@OneToMany 단방향의 문제는 주인과 FK가 서로 다른 테이블에 있다는 점입니다. 효율적이려면 FK를 직접 가진 쪽이 주인이어야 하는데, @OneToMany 단방향은 FK가 없는 Member를 주인으로 삼습니다. 정작 FK(member_id)는 orders 테이블에 있으니, Member가 자기 것이 아닌 orders의 FK를 원격으로 채워야 해서 추가 쿼리가 생깁니다.
SVG 코드
<svg xmlns="http://www.w3.org/2000/svg" width="440" height="300" viewBox="0 0 440 300" font-family="-apple-system, 'Segoe UI', 'Noto Sans KR', sans-serif">
<defs><marker id="ah" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" fill="#888"/></marker></defs>
<rect x="0" y="0" width="440" height="300" fill="#FFFFFF"/>
<rect x="60" y="16" width="320" height="52" rx="6" fill="#FFFBEA" stroke="#E0A000"/>
<text x="220.0" y="38.5" font-size="12" fill="#5A4300" text-anchor="middle" font-weight="bold">Member (ONE 쪽, @OneToMany 단방향)</text>
<text x="220.0" y="53.5" font-size="10.5" fill="#444" text-anchor="middle">FK 컬럼이 없다</text>
<rect x="60" y="232" width="320" height="52" rx="6" fill="#E9F2E9" stroke="#8FBF8F"/>
<text x="220.0" y="254.5" font-size="12" fill="#2E6B2E" text-anchor="middle" font-weight="bold">orders 테이블 (MANY 쪽)</text>
<text x="220.0" y="269.5" font-size="10.5" fill="#444" text-anchor="middle">id | member_id ← FK는 여기 있다</text>
<line x1="150" y1="68" x2="150" y2="231" stroke="#888" stroke-width="1.2" marker-end="url(#ah)"/>
<text x="166" y="112" font-size="11" fill="#333" text-anchor="start">주인인데 내 테이블엔</text>
<text x="166" y="128" font-size="11" fill="#333" text-anchor="start">FK가 없어서</text>
<text x="166" y="144" font-size="11" fill="#333" text-anchor="start">orders.member_id를</text>
<text x="166" y="160" font-size="11" fill="#333" text-anchor="start">원격으로 채움</text>
<text x="166" y="176" font-size="11" fill="#333" text-anchor="start">→ INSERT 뒤 별도 UPDATE</text>
</svg>
문제 1 — @JoinColumn이 없으면 조인 테이블이 생긴다
@Entity
class Member {
@Id @GeneratedValue
Long id;
@OneToMany // @JoinColumn 없음
List<Order> orders = new ArrayList<>();
}
이렇게 하면 Hibernate는 FK를 어디에 둘지 몰라, 중간 조인 테이블(member_orders) 을 만들어 다대다처럼 관리합니다. 테이블이 하나 더 생기고, 조회, 저장 때마다 그 테이블을 거쳐 쿼리가 복잡해집니다.
SVG 코드
<svg xmlns="http://www.w3.org/2000/svg" width="440" height="250" viewBox="0 0 440 250" font-family="-apple-system, 'Segoe UI', 'Noto Sans KR', sans-serif">
<defs><marker id="ah" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" fill="#888"/></marker></defs>
<rect x="0" y="0" width="440" height="250" fill="#FFFFFF"/>
<rect x="30" y="16" width="200" height="44" rx="6" fill="#EEF3FB" stroke="#4C7FE0"/>
<text x="130.0" y="34.5" font-size="12" fill="#26508F" text-anchor="middle" font-weight="bold">member</text>
<text x="130.0" y="49.5" font-size="10.5" fill="#444" text-anchor="middle">(id)</text>
<rect x="30" y="96" width="200" height="60" rx="6" fill="#FCE4EC" stroke="#D06A86"/>
<text x="130.0" y="115.0" font-size="12" fill="#9E3A57" text-anchor="middle" font-weight="bold">member_orders</text>
<text x="130.0" y="130.0" font-size="10.5" fill="#444" text-anchor="middle">(member_id, orders_id)</text>
<text x="130.0" y="145.0" font-size="10.5" fill="#444" text-anchor="middle">← 의도치 않은 조인 테이블</text>
<rect x="30" y="192" width="200" height="44" rx="6" fill="#E9F2E9" stroke="#8FBF8F"/>
<text x="130.0" y="210.5" font-size="12" fill="#2E6B2E" text-anchor="middle" font-weight="bold">orders</text>
<text x="130.0" y="225.5" font-size="10.5" fill="#444" text-anchor="middle">(id, ...)</text>
<line x1="130" y1="60" x2="130" y2="95" stroke="#888" stroke-width="1.2" marker-end="url(#ah)"/>
<line x1="130" y1="156" x2="130" y2="191" stroke="#888" stroke-width="1.2" marker-end="url(#ah)"/>
<line x1="230" y1="126" x2="252" y2="126" stroke="#E0A000" stroke-dasharray="3 3"/>
<rect x="252" y="92" width="176" height="68" rx="6" fill="#FFFBEA" stroke="#E0A000" stroke-dasharray="5 4"/>
<text x="340.0" y="110" font-size="10.5" fill="#5A4300" text-anchor="middle">@OneToMany 단방향 +</text>
<text x="340.0" y="126" font-size="10.5" fill="#5A4300" text-anchor="middle">@JoinColumn 없음</text>
<text x="340.0" y="142" font-size="10.5" fill="#5A4300" text-anchor="middle">→ 중간 테이블로 관리</text>
</svg>
문제 2 — @JoinColumn을 사용해도 추가 UPDATE가 발생한다
조인 테이블이 싫어 @JoinColumn으로 orders.member_id에 직접 매핑해도 문제가 남습니다.
@Entity
class Member {
@Id @GeneratedValue
Long id;
@OneToMany
@JoinColumn(name = "member_id") // orders.member_id에 매핑
List<Order> orders = new ArrayList<>();
}
member.getOrders().add(order)로 주문을 추가해 저장하면, Order 엔티티는 자기 member_id를 모릅니다(단방향이라 Order에 Member 참조가 없음). 그래서 Hibernate는 일단 FK를 비운 채 INSERT한 뒤, 컬렉션을 보고 별도 UPDATE로 FK를 채웁니다.
INSERT INTO member (id) VALUES (?);
INSERT INTO orders (id, member_id) VALUES (?, NULL); -- 자식이 부모를 모름
UPDATE orders SET member_id = ? WHERE id = ?; -- 추가 UPDATE
주문 한 건마다 INSERT + UPDATE가 나가므로, 벌크로 쌓을수록 쿼리가 두 배로 늘고 원인도 눈에 잘 띄지 않습니다. 이게 @OneToMany 단방향을 피하는 가장 큰 이유입니다.
문제 3 — 한 방향으로만 탐색되고, 방향이 헷갈린다
단방향은 말 그대로 한쪽에서만 상대를 참조합니다. 그래서 반대 방향 탐색이 막힙니다.
@ManyToOne단방향(Order→Member):order.getMember()는 되지만member.getOrders()는 없습니다(부모에서 자식 목록을 볼 수 없음).@OneToMany단방향(Member→Order):member.getOrders()는 되지만order.getMember()는 없습니다(자식에서 부모를 볼 수 없음).
어느 쪽을 택하든 필요한 탐색이 막힐 수 있습니다. 특히 @OneToMany 단방향이 헷갈리는 이유는 이렇습니다 — 채워야 할 FK는 orders 테이블의 member_id 컬럼입니다. 상식적으로는 "그 컬럼이 orders에 있으니 Order를 저장할 때 Order 쪽이 채운다"고 보게 됩니다. 그런데 @OneToMany 단방향에서는 그 member_id를 Order가 아니라 Member의 컬렉션(@OneToMany)이 관리합니다. 컬럼이 있는 곳(orders)과 그 값을 채우는 코드(Member)가 서로 달라서, 코드만 봐서는 누가 FK를 채우는지 헷갈립니다.
해결 방향
1) 다대일 단방향(@ManyToOne)을 기본으로
가장 단순한 해결은 연관관계를 FK 가진 쪽(Order)에서 @ManyToOne 단방향으로 거는 것입니다. 추가 UPDATE도, 조인 테이블도 없습니다. 부모에서 자식으로 탐색할 일이 없다면 여기서 끝내면 됩니다.
2) 역방향 탐색이 필요하면 — 양방향으로 보완
member.getOrders()처럼 부모에서 자식을 탐색해야 한다면, @ManyToOne(주인)은 그대로 유지하고 부모에 @OneToMany(mappedBy)를 추가합니다. mappedBy는 "FK 관리는 Order.member가 한다"는 선언이라, 테이블 구조도 쿼리도 1)과 똑같고 객체 탐색만 양쪽으로 열립니다.
@Entity
class Member {
@Id @GeneratedValue
Long id;
@OneToMany(mappedBy = "member") // 주인 아님(읽기 전용) — 추가 쿼리 없음
List<Order> orders = new ArrayList<>();
}
@Entity
class Order {
@Id @GeneratedValue
Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "member_id") // 주인(FK)
Member member;
}
3) 양방향을 쓸 때의 주의점
양방향은 편리하지만 두 가지를 챙겨야 합니다.
-
연관관계 편의 메서드로 양쪽을 함께 세팅 — 주인(
Order.member)만 세팅하면 DB는 맞지만, 영속성 컨텍스트 안의 부모 컬렉션은 갱신되지 않아 조회 값이 맞지 않을 수 있습니다. 한 메서드에서 양쪽을 동기화합니다.// Member
void addOrder(Order order) {
orders.add(order);
order.setMember(this); // 주인 쪽도 함께 세팅
} -
무한 재귀 차단 —
Member↔Order가 서로 참조하므로, 롬복@ToString이나 JSON 직렬화가 순환 참조를 따라 무한히 반복돼StackOverflowError에 이릅니다.@ToString에서 연관 필드를 빼고(exclude), API 응답은 엔티티 대신 DTO로 변환하거나@JsonIgnore로 순환을 차단합니다.@Entity
class Member {
@OneToMany(mappedBy = "member")
@ToString.Exclude // 롬복 toString이 orders를 타고 순환하지 않도록 제외
@JsonIgnore // JSON 직렬화가 orders↔member 순환하지 않도록 차단
List<Order> orders = new ArrayList<>();
}
// 가장 깔끔한 방법은 엔티티를 그대로 응답하지 않고 필요한 필드만 DTO로 변환해 반환하는 것입니다.
언제 단방향으로 충분한가 — 판단 기준
SVG 코드
<svg xmlns="http://www.w3.org/2000/svg" width="440" height="352" viewBox="0 0 440 352" font-family="-apple-system, 'Segoe UI', 'Noto Sans KR', sans-serif">
<defs><marker id="ah" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" fill="#888"/></marker></defs>
<rect x="0" y="0" width="440" height="352" fill="#FFFFFF"/>
<g transform="translate(0,-28)">
<circle cx="220" cy="44" r="7" fill="#555"/>
<line x1="220" y1="51" x2="220" y2="65" stroke="#888" stroke-width="1.2" marker-end="url(#ah)"/>
<rect x="120" y="66" width="200" height="32" rx="6" fill="#F7F7F7" stroke="#999999"/>
<text x="220.0" y="86.0" font-size="11.5" fill="#444" text-anchor="middle">연관관계를 매핑한다</text>
<line x1="220" y1="98" x2="220" y2="115" stroke="#888" stroke-width="1.2" marker-end="url(#ah)"/>
<rect x="90" y="116" width="260" height="32" rx="6" fill="#EEF3FB" stroke="#4C7FE0"/>
<text x="220.0" y="136.0" font-size="11.5" fill="#444" text-anchor="middle">FK를 가진 쪽에 @ManyToOne 단방향</text>
<line x1="220" y1="148" x2="220" y2="165" stroke="#888" stroke-width="1.2" marker-end="url(#ah)"/>
<rect x="150" y="166" width="140" height="46" rx="6" fill="#FFF3E0" stroke="#E0A000"/>
<text x="220.0" y="185.5" font-size="11.5" fill="#444" text-anchor="middle">부모에서 자식 목록을</text>
<text x="220.0" y="200.5" font-size="11.5" fill="#444" text-anchor="middle">탐색해야 하나?</text>
<polyline points="150,189 92,189 92,239" fill="none" stroke="#888" stroke-width="1.2" marker-end="url(#ah)"/>
<text x="120" y="183" font-size="10.5" fill="#9E3A57" text-anchor="middle" font-weight="bold">N</text>
<rect x="12" y="240" width="160" height="32" rx="6" fill="#E9F2E9" stroke="#8FBF8F"/>
<text x="92.0" y="260.0" font-size="11" fill="#444" text-anchor="middle">여기서 끝 - 단방향으로 충분</text>
<line x1="92" y1="272" x2="92" y2="287" stroke="#888" stroke-width="1.2" marker-end="url(#ah)"/>
<circle cx="92" cy="296" r="8" fill="#FFFFFF" stroke="#555" stroke-width="1.5"/>
<circle cx="92" cy="296" r="4.5" fill="#555"/>
<polyline points="290,189 312,189 312,239" fill="none" stroke="#888" stroke-width="1.2" marker-end="url(#ah)"/>
<text x="300" y="183" font-size="10.5" fill="#9E3A57" text-anchor="middle" font-weight="bold">Y</text>
<rect x="196" y="240" width="232" height="46" rx="6" fill="#EEF3FB" stroke="#4C7FE0"/>
<text x="312.0" y="259.5" font-size="11.5" fill="#444" text-anchor="middle">부모에 @OneToMany(mappedBy) 추가</text>
<text x="312.0" y="274.5" font-size="11.5" fill="#444" text-anchor="middle">(양방향)</text>
<line x1="312" y1="286" x2="312" y2="303" stroke="#888" stroke-width="1.2" marker-end="url(#ah)"/>
<rect x="196" y="304" width="232" height="46" rx="6" fill="#EEF3FB" stroke="#4C7FE0"/>
<text x="312.0" y="323.5" font-size="11.5" fill="#444" text-anchor="middle">연관관계 편의 메서드로 동기화</text>
<text x="312.0" y="338.5" font-size="11.5" fill="#444" text-anchor="middle">직렬화 순환 차단</text>
<line x1="312" y1="350" x2="312" y2="363" stroke="#888" stroke-width="1.2" marker-end="url(#ah)"/>
<circle cx="312" cy="372" r="8" fill="#FFFFFF" stroke="#555" stroke-width="1.5"/>
<circle cx="312" cy="372" r="4.5" fill="#555"/>
</g>
</svg>
@ManyToOne단방향 — FK 가진 쪽에서만 참조하면 되는 대부분의 경우. 기본값으로 삼습니다.- 양방향 — 부모에서 자식 컬렉션 탐색이 실제로 필요할 때만.
@OneToMany는 항상mappedBy로 읽기 전용이어야 합니다. @OneToMany단방향(주인) —mappedBy없이 부모가 컬렉션을 주인으로 관리하는 형태. 조인 테이블과 추가 UPDATE 때문에 특별한 이유가 없으면 사용하지 않습니다.
정리
- 연관관계의 주인은 FK를 가진 쪽입니다 — 이 원칙을 어기면 DB가 FK를 채우려고 추가 쿼리를 발생시킵니다.
@OneToMany단방향은@JoinColumn이 없으면 조인 테이블, 있어도 INSERT 후 추가 UPDATE가 발생합니다.- 기본은
@ManyToOne단방향, 부모→자식 탐색이 필요할 때만@OneToMany(mappedBy)로 양방향 보완(테이블, 쿼리 영향 없음). - 양방향은 연관관계 편의 메서드로 양쪽을 동기화하고, 직렬화 순환(
@ToString, JSON)을 차단합니다.
