JAVA 자료구조 [JPA] 복합키

2019.02.26 03:06

졸리운_곰 조회 수:197

[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

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
38 Spring Batch 간단 정리 Sprong Batch 기초를 알아보자 file 졸리운_곰 2020.10.13 198
37 Spring Batch - ItemReader, ItemWriter, ItemProcessor 졸리운_곰 2020.10.13 370
36 spring batch» Spring Batch Tasklet Example file 졸리운_곰 2020.10.12 198
35 Spring Batch Example 2 - 간단한 Job만들기 file 졸리운_곰 2020.10.12 151
34 Spring batch Job 설정과 실행하기 file 졸리운_곰 2020.10.12 206
33 [Spring Batch] Configuring and Running a Job file 졸리운_곰 2020.10.12 121
32 [스프링] 스프링 배치 기본 개념 file 졸리운_곰 2019.12.24 244
31 Spring Batch 개념 정리 file 졸리운_곰 2019.12.24 257
30 스프링 배치 개발가이드 졸리운_곰 2019.12.24 321
29 Quartz + Spring Batch 조합! Quartz Scheduler 와 Spring Batch 의 궁합과 조합을 정리. file 졸리운_곰 2019.12.24 882
28 Spring Batch 간단 정리 file 졸리운_곰 2019.12.24 421
27 spring batch 소개 file 졸리운_곰 2019.12.24 208
26 Spring Batch - 소개 file 졸리운_곰 2019.12.24 207
25 Spring Batch Multithreading Example file 졸리운_곰 2019.01.31 285
24 Spring batch를 Parallel로 돌려보자 졸리운_곰 2019.01.31 399
23 Spring MVC 주요 애노테이션(Annotation)정리 file 졸리운_곰 2018.12.29 268
22 스프링/스프링부트 애노테이션(Annotation) 정리 졸리운_곰 2018.12.29 385
21 Spring Framework - annotation 정리 #1 졸리운_곰 2018.12.29 321
20 [Spring] Annotation 정리 졸리운_곰 2018.12.29 272
19 Maven 기초 사용법 졸리운_곰 2018.04.15 322
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED