-
[Spring] @GeneratedValue | 엔티티의 기본 키 생성 전략Spring 2023. 6. 18. 17:23
🔍 @GeneratedValue
/* * Copyright (c) 2008, 2020 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0, * or the Eclipse Distribution License v. 1.0 which is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause */ // Contributors: // Linda DeMichiel - 2.1 // Linda DeMichiel - 2.0 package jakarta.persistence; import java.lang.annotation.Target; import java.lang.annotation.Retention; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import static jakarta.persistence.GenerationType.AUTO; /** * Provides for the specification of generation strategies for the * values of primary keys. * * <p> The <code>GeneratedValue</code> annotation * may be applied to a primary key property or field of an entity or * mapped superclass in conjunction with the {@link Id} annotation. * The use of the <code>GeneratedValue</code> annotation is only * required to be supported for simple primary keys. Use of the * <code>GeneratedValue</code> annotation is not supported for derived * primary keys. * * <pre> * * Example 1: * * @Id * @GeneratedValue(strategy=SEQUENCE, generator="CUST_SEQ") * @Column(name="CUST_ID") * public Long getId() { return id; } * * Example 2: * * @Id * @GeneratedValue(strategy=TABLE, generator="CUST_GEN") * @Column(name="CUST_ID") * Long id; * </pre> * * @see Id * @see TableGenerator * @see SequenceGenerator * * @since 1.0 */ @Target({METHOD, FIELD}) @Retention(RUNTIME) public @interface GeneratedValue { /** * (Optional) The primary key generation strategy * that the persistence provider must use to * generate the annotated entity primary key. */ GenerationType strategy() default AUTO; /** * (Optional) The name of the primary key generator * to use as specified in the {@link SequenceGenerator} * or {@link TableGenerator} annotation. * <p> Defaults to the id generator supplied by persistence provider. */ String generator() default ""; }
🔍 GenerationType
/* * Copyright (c) 2008, 2022 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0, * or the Eclipse Distribution License v. 1.0 which is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause */ // Contributors: // Linda DeMichiel - 2.1 // Linda DeMichiel - 2.0 package jakarta.persistence; /** * Defines the types of primary key generation strategies. * * @see GeneratedValue * * @since 1.0 */ public enum GenerationType { /** * Indicates that the persistence provider must assign * primary keys for the entity using an underlying * database table to ensure uniqueness. */ TABLE, /** * Indicates that the persistence provider must assign * primary keys for the entity using a database sequence. */ SEQUENCE, /** * Indicates that the persistence provider must assign * primary keys for the entity using a database identity column. */ IDENTITY, /** * Indicates that the persistence provider must assign * primary keys for the entity by generating an RFC 4122 * Universally Unique IDentifier. */ UUID, /** * Indicates that the persistence provider should pick an * appropriate strategy for the particular database. The * <code>AUTO</code> generation strategy may expect a database * resource to exist, or it may attempt to create one. A vendor * may provide documentation on how to create such resources * in the event that it does not support schema generation * or cannot create the schema resource at runtime. */ AUTO }
GenerationType은 enum 타입으로 TABLE, SEQUENCE, IDENTITY, UUID, AUTO 5개의 값을 가질 수 있다.
- TABLE: 데이터베이스에 키 생성 전용 테이블을 하나 만들고 이를 사용하여 기본키 생성
- SEQUENCE: 데이터베이스의 특별한 오브젝트 시퀀스를 사용하여 기본키 생성
- IDENTITY: 기본키 생성을 데이터베이스에 위임 ex) MySQL - AUTO_INCREMENT
- AUTO: JPA 구현체가 자동으로 생성 전략 결정
🔍 어떤 전략을 사용해야 하는가?
Entity의 Primary Key는 Long 타입의 Auto_increment를 사용하는 게 좋다.
주민등록번호와 같이 비즈니스상 Unique Key나, 여러 키를 조합한 복합키로 PK를 잡을 경우 난감한 상황이 종종 발생한다.
- Foriegn Key를 맺을 때 다른 테이블에서 복합키 전부를 갖고 있거나, 중간 테이블을 하나 더 둬야 하는 상황 발생
- 인덱스에 좋은 영향 X
- 유니크한 조건이 변경될 경우 PK 전체를 수정해야 하는 일 발생
* 주민등록번호, 복합키 등은 Unique Key로 별도로 추가하는 것이 좋다
📋 참고 자료
+ 스프링 부트와 AWS로 혼자 구현하는 웹 서비스
728x90'Spring' 카테고리의 다른 글
[Spring] Kafka 채팅 기능 구현 - 1 (0) 2023.12.19 [QueryDSL] QueryDSL에서 조인 시 주의사항 | 객체 그래프 탐색 (2) 2023.10.22 [Spring] TDD와 단위 테스트 (0) 2023.06.18 [Spring] Spring Security + JWT 로그인 구현하기 - 4 (6) 2023.06.16 [Spring] Spring Security + JWT 로그인 구현하기 - 3 (0) 2023.06.15