블로그 이미지

suddiyo


꾸준히 기록하고 성장하는 백엔드 개발자 💻
Today
-
Yesterday
-
Total
-

ABOUT ME

-

  • [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:
     *
     *     &#064;Id
     *     &#064;GeneratedValue(strategy=SEQUENCE, generator="CUST_SEQ")
     *     &#064;Column(name="CUST_ID")
     *     public Long getId() { return id; }
     *
     *     Example 2:
     *
     *     &#064;Id
     *     &#064;GeneratedValue(strategy=TABLE, generator="CUST_GEN")
     *     &#064;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로 별도로 추가하는 것이 좋다

     


    📋 참고 자료

     

    GeneratedValue (Java(TM) EE 7 Specification APIs)

    Provides for the specification of generation strategies for the values of primary keys. The GeneratedValue annotation may be applied to a primary key property or field of an entity or mapped superclass in conjunction with the Id annotation. The use of the

    docs.oracle.com

     

    @Id / @GeneratedValue에 대해 알아보자

    @Id / @GeneratedValue에 대해 알아보자 PK를 나타내기 위해 @Id 어노테이션을 사용하며, 생성 전략을 정의하기 위해 @GeneratedValue 를 사용한다. 해당 어노테이션에 대해서 알아보도록 하자. @Id package javax

    rutgo-letsgo.tistory.com

    + 스프링 부트와 AWS로 혼자 구현하는 웹 서비스

    728x90

    댓글

Designed by Tistory.