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

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
27 [java][maven] jar 파일 의존성 한번에 다운로드 maven 사용 졸리운_곰 2023.08.24 192
26 Prometheus + Grafana로 Java 애플리케이션 모니터링하기 file 졸리운_곰 2020.12.17 279
25 Blockchain Implementation With Java Code file 졸리운_곰 2019.06.16 338
24 Java 코드로 이해하는 블록체인(Blockchain) 졸리운_곰 2019.06.16 377
23 순수 Java Application 코드로 Restful api 호출 졸리운_곰 2018.10.10 415
22 WebDAV 구현을 위한 환경 설정 file 졸리운_곰 2017.09.24 268
21 [Java] Apache Commons HttpClient로 SSL 통신하기 졸리운_곰 2017.03.27 784
20 JSoup를 이용한 HTML 파싱 졸리운_곰 2017.03.04 320
19 jsoup을 활용해서 Java에서 HTML 파싱하는 방법 정리 file 졸리운_곰 2017.03.04 579
18 NSA의 Dataflow 엔진 Apache NiFi 소개와 설치 file 졸리운_곰 2017.01.23 630
17 wordpress-java-integration 자바와 워드프레스 통합 졸리운_곰 2016.12.30 298
16 Create New Posts in Wordpress using Java and XMLRpc 졸리운_곰 2016.11.14 268
15 자바로 POST 방식으로 통신하기, java httppost 클래스를 활용한 예제 졸리운_곰 2016.11.14 647
14 [Java]아파치 HttpClient사용하기 file 졸리운_곰 2016.11.14 301
13 Building a Search Engine With Nutch Solr And Hadoop file 졸리운_곰 2016.04.21 435
12 Nutch and Hadoop Tutorial file 졸리운_곰 2016.04.21 391
11 Latest step by Step Installation guide for dummies: Nutch 0. file 졸리운_곰 2016.04.21 305
10 Nutch 초간단 빌드와 실행 졸리운_곰 2016.04.21 681
9 Nutch로 알아보는 Crawling 구조 - Joinc 졸리운_곰 2016.04.21 536
8 A tiny bittorrent library Java: 자바로 만든 작은 bittorrent 라이브러리 file 졸리운_곰 2016.04.20 418
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED