JAVA 자료구조 [JPA] 복합키

2019.02.26 03:06

졸리운_곰 조회 수:200

[JPA] 복합키

 

대부분의 엔티티에는 @Id 애노테이션을 한 개 사용한다.

하지만 테이블의 키가 복합키로 이뤄져 있다면 엔티티를 설계할 때에 이를 고려해야 한다.

복합키 설정 방법은 두 가지가 있다. 

1
2
@Embeddable 이용하는 방법
@IdClass 이용하는 방법
cs

 

첫 번째 방법이 객체지향 방식에 가깝다고 한다.

두 번째 방법은 DB 방식에 가깝다고 하는데 잘 와닿지는 않는다.

 

 

@Embeddable 이용 방법


다음과 같이 emp 테이블이 존재한다.

emp 테이블의 키는 emp_name, emp_no 두 개의 복합키로 이뤄져 있다.

1
2
3
4
5
6
create table emp (
    emp_name varchar(255not null,
    emp_no integer not null,
    name varchar(255),
    primary key (emp_name, emp_no)
)
cs

 

@EmbeddedId 를 이용하여 엔티티를 설계할 때에는 우선 Serializable 인터페이스를 구현한 클래스를 선언하고 필드에 복합키로 사용되는 컬럼을 선언하면 된다.

그리고 @Embeddable 애노테이션을 추가해 주자.

1
2
3
4
5
6
7
8
9
10
@Data
@Embeddable
class EmpId implements Serializable {
 
    @Column(name = "EMP_NO")
    private int empNo;
 
    @Column(name = "EMP_NAME")
    private String empName;
}
cs

 

복합키에 대한 클래스를 생성했으니 이를 엔티티와 결합시켜야 한다.

방법은 간단하다.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

Emp 엔티티 클래스 내부에 복합키를 위한 클래스인 EmpId를 객체 연관 관계로 설정하면 된다.

그리고 @EmbeddedId 애노테이션을 붙여주면 설정 끝

1
2
3
4
5
6
7
8
9
@Data
@Entity
class Emp {
 
    @EmbeddedId
    private EmpId empId;
 
    private String phone;
}
cs

 

테스트를 해보자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Test
@Transactional
public void testEmbeddable() {
    EmpId empId = new EmpId();
    empId.setEmpNo(1);
    empId.setEmpName("nklee");
 
    Emp emp = new Emp();
    emp.setEmpId(empId);
    emp.setPhone("010-1111-1111");
 
    em.persist(emp);
    em.flush();
    em.clear();
 
    emp = em.find(Emp.class, empId);
    assertThat(1, is(emp.getEmpId().getEmpNo()));
    assertThat("nklee", is(emp.getEmpId().getEmpName()));
}
cs

 

 

@IdClass 이용 방법


order_id, product_id 복합키를 가지는 order_product 테이블이 존재한다.

1
2
3
4
5
6
create table order_product (
    order_id integer not null,
    product_id integer not null,
    amount integer not null,
    primary key (order_id, product_id)
)
cs

 

Serializable 인터페이스를 구현한 클래스를 선언하고 필드를 정의하자.

1
2
3
4
5
@Data
class OrderProductPK implements Serializable {
    private int orderId;
    private int productId;
}
cs

 

위와 같이 정의한 후 엔티티 클래스에 @IdClass(OrderProductPK.class) 설정을 추가해 주면 된다.

유의해야 할 부분은 OrderProduct 엔티티의 식별자 orderId 필드 이름이 OrderProductPK의 orderId 필드 이름과 같아야 한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Data
@Entity
@IdClass(OrderProductPK.class)
class OrderProduct {
 
    @Id
    @Column(name = "ORDER_ID")
    private int orderId;
 
    @Id
    @Column(name = "PRODUCT_ID")
    private int productId;
 
    private int amount;
}
cs

 

테스트 해보자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Test
@Transactional
public void testIdClass() {
    OrderProduct orderProduct = new OrderProduct();
    orderProduct.setOrderId(1);
    orderProduct.setProductId(2);
    orderProduct.setAmount(1000);
 
    em.persist(orderProduct);
    em.flush();
    em.clear();
 
    OrderProductPK pk = new OrderProductPK();
    pk.setOrderId(1);
    pk.setProductId(2);
 
    orderProduct = em.find(OrderProduct.class, pk);
    assertThat(1, is(orderProduct.getOrderId()));
    assertThat(2, is(orderProduct.getProductId()));
    assertThat(1000, is(orderProduct.getAmount()));
}
cs
 

[출처] https://lng1982.tistory.com/286

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
101 Java Byte Array to InputStream 졸리운_곰 2019.10.24 176
100 [JAXB] JAXB Annotation 설명~ Part. 2 졸리운_곰 2019.10.24 305
99 [JAXB] JAXB Annotation 설명~ Part. 1 졸리운_곰 2019.10.24 136
98 JAXB (3) - marshal, unmarshal에 대해 알아보자. file 졸리운_곰 2019.10.24 142
97 JAXB (2) - XML Schema를 Java Interfaces & Classes로 Binding Compile 하기 file 졸리운_곰 2019.10.24 144
96 JAXB (1) - JAXB 란? file 졸리운_곰 2019.10.24 188
95 XStream으로 자바 객체를 XML로 직렬화하기 file 졸리운_곰 2019.10.15 249
94 [번역] XStream 배우기 : 2분만에 배우는 XStream 졸리운_곰 2019.10.15 232
93 java XML Parser 정리 졸리운_곰 2019.10.05 175
92 [JPA] 쿼리메서드 : 쿼리 연습 조회(findBy..) , 페이징처리 졸리운_곰 2019.03.24 1776
91 스프링 데이터 JPA 레퍼런스 번역 file 졸리운_곰 2019.03.24 1142
90 JPA 개념, class05 JPA 환경설정 졸리운_곰 2019.03.24 209
89 [자바코드] 고유값인 UUID, GUID 생성하기 졸리운_곰 2019.02.27 377
» [JPA] 복합키 졸리운_곰 2019.02.26 200
87 jpa muli row select result is same row repeat Java 자바 Jpa에서 멀티 로우 반환시 같은값이 반복 file 졸리운_곰 2019.01.01 297
86 [자바] 리스트를 순회하는 방법 졸리운_곰 2018.12.31 277
85 SpringBoot JPA 예제 졸리운_곰 2018.12.31 230
84 SpringBoot JPA 예제(1:N, 양방향) 졸리운_곰 2018.12.31 187
83 SpringBoot JPA 예제(결합 인덱스) 졸리운_곰 2018.12.31 234
82 SpringBoot JPA 예제(@ManyToOne, 단방향) 졸리운_곰 2018.12.31 300
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED