스프링에서 Entity를 복합키로 설정하여 설계할 때 JPA에서는 2가지 방법을 알려준다.
1. @Embeddable
2. @IdClass
2가지 방법이 있다.
@Embeddable
객체지향 방식에 가깝다고 한다.
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Entity
public class Fruit {
@EmbeddedId
private FruitId id;
private String name;
}
Fruit 엔티티에 식별자 클래스를 직접 사용하고 @EmbeddedId 어노테이션을 적여주면 된다.
@NoArgsConstructor
@AllArgsConstructor
@Embeddable
public class FruitId implements Serializable {
private String id;
private String code;
}
복합 키에 대한 클래스를 생성하고 @Embeddable을 추가한다.
@EmbeddedId를 이용하여 엔터티를 설계할 때는 우선 Serializable 인터페이스를 선언하고 복합키로 사용할 컬럼을 추가해 주면 된다.
@IdClass
관계형 DB방식에 가깝다고 한다.
@Entity
@IdClass(FuitId.class)
public class Fruit {
@id
private String id;
@id
private String code;
private String name;
}
엔티티 클레스에 @IdClass(Fruit.class) 설정을 추가해 주면 된다.
@Data
public class FuitId implements Serializable {
private String id;
private String code;
}
Serializable 인터페이스를 선언하고 필드를 정의해 주면 된다.
@NoArgsConstructor : 어노테이션은 파라미터가 없는 기본 생성자를 생성해 준다.
@AllArgsConstructor : 어노테이션은 모든 필드 값을 파라미터로 받는 생성자를 만들어 준다.
'개발 > Spring' 카테고리의 다른 글
[Spring] @ComponentScan, @EnableJpaRepositories, @EntityScan (0) | 2022.03.04 |
---|---|
[Spring] JPA 기본 키 생성 전략 (0) | 2022.03.02 |
[Spring] @transactional 동작 원리 (0) | 2022.02.23 |
[Spring] JPA 잠금(Lock) 이해하기 (0) | 2022.02.15 |