0+ 스프링/0 + SpringBoot(스프링부트)

JPA 복합키 사용방법(@IdClass, @EmbeddedId)

힘들면힘을내는쿼카 2022. 6. 2. 19:13
728x90
반응형

 

 

 

실무에서 JPA를 이용하여 개발하던 중에 

이와 같은 경고 메시지를 받게 되었다..😫

 

경고이니 처음에는 그냥 개발했는데,,

그래도 이건 아니다 싶어 알아보았다.

 

우선 JPA에서 PK가 단일 키 일때는 @Id를 이용하여 쉽게 Entity를 구현했다.

하지만, 복합키인 경우가 있기 때문에 아래와 같은 설정을 해줘야한다.

복합키를 구성하기 위해서는 필수 조건이 있다.

1. @EmbeddedId 또는 @IdClass
2. public의 no-args constructor
3. serializable을 상속 받기
4. equals(), hashCode() Override

 

 

여기서는 @IdClass를 이용하여 구현한 예제를 만들어 보겠습니다.

(@EmbeddedId를 이용한 예시는 아래의 블로그 링크로 방문해주세요)

https://kha0213.github.io/jpa/jpa-composite-key/

 

JPA Composite Primary Key

JPA Composite Primary Key JPA에서 Primary Key가 단일 키 일때는 @ID annotation으로 쉽게 가능하였다. 하지만 실무에서는 복합키인 경우도 많고 JPA에서는 이 기능을 지원하기 때문에 학습해 보았다. 크게 두

kha0213.github.io

 

 

1. Entity의 id만 있는 클래스를 정의 한다.(lombook을 사용했다.)

@Getter
@EqualsAndHashCode
@NoArgsConstructor
@AllArgsConstructor
public class CpId implements Serializable {
    private int cs_id;
    private int cp_id;
}

 

2. Entity를 정의한다.

@Entity
@Getter @NoArgsConstructor
@IdClass(CpId.class)
@Table(name = "TB_CP")
public class Cp implements Serializable {
    @Id
    private int cs_id;
    @Id
    private int cp_id;
    private int bank_id;
    private int charger_capacity;
    private String protocol;
    private String id_token;
    private int gun1_capacity;
    private String gun1_ide;
    private int gun2_capacity;
    private String gun2_ide;
    private int acb_id;
    private LocalDateTime expiry_date;
    private int status;

    @Builder
    public Cp(int cs_id, int cp_id, int bank_id, int charger_capacity, String protocol, String id_token, int gun1_capacity, String gun1_ide, int gun2_capacity, String gun2_ide, int acb_id, LocalDateTime expiry_date, int status) {
        this.cs_id = cs_id;
        this.cp_id = cp_id;
        this.bank_id = bank_id;
        this.charger_capacity = charger_capacity;
        this.protocol = protocol;
        this.id_token = id_token;
        this.gun1_capacity = gun1_capacity;
        this.gun1_ide = gun1_ide;
        this.gun2_capacity = gun2_capacity;
        this.gun2_ide = gun2_ide;
        this.acb_id = acb_id;
        this.expiry_date = expiry_date;
        this.status = status;
    }
}

 

 

 

경고 없이 테이블이 생성된것을 확인 할 수 있다.

 

 

728x90
반응형