article thumbnail image
Published 2022. 6. 30. 21:53

1. 기본 키 매핑 어노테이션

• @Id 
• @GeneratedValue

@Id @GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

 

2. 기본 키 매핑 방법

• 직접 할당: @Id만 사용
• 자동 생성(@GeneratedValue) 
• IDENTITY: 데이터베이스에 위임, MYSQL 
• SEQUENCE: 데이터베이스 시퀀스 오브젝트 사용, ORACLE 
• @SequenceGenerator 필요
• TABLE: 키 생성용 테이블 사용, 모든 DB에서 사용
• @TableGenerator 필요
• AUTO: 방언에 따라 자동 지정, 기본값

 

3. IDENTITY 전략 - 특징

• 기본 키 생성을 데이터베이스에 위임
• 주로 MySQL, PostgreSQL, SQL Server, DB2에서 사용
(예: MySQL의 AUTO_ INCREMENT) 
• JPA는 보통 트랜잭션 커밋 시점에 INSERT SQL 실행
• AUTO_ INCREMENT는 데이터베이스에 INSERT SQL을 실행한 이후에 ID 값을 알 수 있음
• IDENTITY 전략은 em.persist() 시점에 즉시 INSERT SQL 실행하고 DB에서 식별자를 조회

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private String id;
Hibernate: 
    /* insert hellojpa.Member
        */ insert 
        into
            Member
            (id, name) 
        values
            (null, ?)

Member member = new Member();
            member.setUsername("C");

            System.out.println("============================");

            em.persist(member);

            System.out.println("member.id() = " + member.getId());
            System.out.println("============================");

            tx.commit();
============================
Hibernate: 
    select
        tbl.next_val 
    from
        MY_SEQUENCES tbl 
    where
        tbl.sequence_name=? for update
            
Hibernate: 
    update
        MY_SEQUENCES 
    set
        next_val=?  
    where
        next_val=? 
        and sequence_name=?
member.id() = 1
============================
Hibernate: 
    /* insert hellojpa.Member
        */ insert 
        into
            Member
            (name, id) 
        values
            (?, ?)

 

4. SEQUENCE 전략 - 특징

• 데이터베이스 시퀀스는 유일한 값을 순서대로 생성하는 특별한 데이터베이스 오브젝트(예: 오라클 시퀀스) 
• 오라클, PostgreSQL, DB2, H2 데이터베이스에서 사용

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;
Hibernate: 
    
    drop sequence if exists hibernate_sequence
Hibernate: create sequence hibernate_sequence start with 1 increment by 1
Hibernate: 
    
    create table Member (
       id bigint not null,
        name varchar(255) not null,
        primary key (id)
    )
Hibernate: 
    call next value for hibernate_sequence
Hibernate: 
    /* insert hellojpa.Member
        */ insert 
        into
            Member
            (name, id) 
        values
            (?, ?)

Hibernate: 
    call next value for hibernate_sequence
Hibernate: 
    /* insert hellojpa.Member
        */ insert 
        into
            Member
            (name, id) 
        values
            (?, ?)

5. SEQUENCE 전략 - 매핑

@Entity 
@SequenceGenerator( 
 name = “MEMBER_SEQ_GENERATOR", 
 sequenceName = “MEMBER_SEQ", //매핑할 데이터베이스 시퀀스 이름
 initialValue = 1, allocationSize = 1) 
public class Member { 
 @Id 
 @GeneratedValue(strategy = GenerationType.SEQUENCE, 
 generator = "MEMBER_SEQ_GENERATOR") 
 private Long id;
@Entity
@SequenceGenerator(name = "member_seq_generator", sequenceName = "member_seq")
public class Member {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "member_seq_generator")
    private Long id;
Hibernate: 
    
    drop table Member if exists
Hibernate: 
    
    drop sequence if exists member_seq
Hibernate: create sequence member_seq start with 1 increment by 50
Hibernate: 
    
    create table Member (
       id bigint not null,
        name varchar(255) not null,
        primary key (id)
    )
Hibernate: 
    call next value for member_seq
Hibernate: 
    call next value for member_seq
Hibernate: 
    /* insert hellojpa.Member
        */ insert 
        into
            Member
            (name, id) 
        values
            (?, ?)

 

6. SEQUENCE - @SequenceGenerator

• 주의: allocationSize 기본값 = 50

Member member = new Member();
            member.setUsername("C");

            System.out.println("============================");

            em.persist(member);

            System.out.println("member.id() = " + member.getId());
            System.out.println("============================");

            tx.commit();
Hibernate: 
    
    drop table Member if exists
Hibernate: 
    
    drop sequence if exists MEMBER_SEQ
Hibernate: create sequence MEMBER_SEQ start with 1 increment by 1
Hibernate: 
    
    create table Member (
       id bigint not null,
        name varchar(255) not null,
        primary key (id)
    )
============================
Hibernate: 
    call next value for MEMBER_SEQ
member.id() = 1
============================
Hibernate: 
    /* insert hellojpa.Member
        */ insert 
        into
            Member
            (name, id) 
        values
            (?, ?)

 

@Entity
@SequenceGenerator(
        name = "MEMBER_SEQ_GENERATOR",
        sequenceName = "MEMBER_SEQ", //매핑할 데이터베이스 시퀀스 이름
        initialValue = 1, allocationSize = 50)
public class Member {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE,
            generator = "MEMBER_SEQ_GENERATOR")
    private Long id;
Member member1 = new Member();
            member1.setUsername("A");
            
            Member member2 = new Member();
            member2.setUsername("B");
            
            Member member3 = new Member();
            member3.setUsername("C");

            System.out.println("============================");

            // em.persist(member1);
            // em.persist(member2);
            // em.persist(member3);

            System.out.println("member.id() = " + member1.getId());
            System.out.println("member.id() = " + member2.getId());
            System.out.println("member.id() = " + member3.getId());
            System.out.println("============================");

            tx.commit();
Hibernate: create sequence MEMBER_SEQ start with 1 increment by 50
============================
member.id() = null
member.id() = null
member.id() = null
============================

 

Member member1 = new Member();
            member1.setUsername("A");

            Member member2 = new Member();
            member2.setUsername("B");

            Member member3 = new Member();
            member3.setUsername("C");

            System.out.println("============================");

            em.persist(member1);
            em.persist(member2);
            em.persist(member3);

            System.out.println("member.id() = " + member1.getId());
            System.out.println("member.id() = " + member2.getId());
            System.out.println("member.id() = " + member3.getId());
            System.out.println("============================");

            tx.commit();
============================
Hibernate: 
    call next value for MEMBER_SEQ
Hibernate: 
    call next value for MEMBER_SEQ
member.id() = 1
member.id() = 2
member.id() = 3
============================
Hibernate: 
    /* insert hellojpa.Member
        */ insert 
        into
            Member
            (name, id) 
        values
            (?, ?)
Hibernate: 
    /* insert hellojpa.Member
        */ insert 
        into
            Member
            (name, id) 
        values
            (?, ?)
Hibernate: 
    /* insert hellojpa.Member
        */ insert 
        into
            Member
            (name, id) 
        values
            (?, ?)

 

7. SEQUENCE 전략과 최적화

1) TABLE 전략

• 키 생성 전용 테이블을 하나 만들어서 데이터베이스 시퀀스를 흉내내는 전략
• 장점: 모든 데이터베이스에 적용 가능
• 단점: 성능

@Entity
@TableGenerator(
        name = "MEMBER_SEQ_GENERATOR",
        table = "MY_SEQUENCES",
        pkColumnValue = "MEMBER_SEQ", allocationSize = 1)
public class Member {

    @Id
    @GeneratedValue(strategy = GenerationType.TABLE,
            generator = "MEMBER_SEQ_GENERATOR")
    private Long id;
Hibernate: 
    
    drop table Member if exists
Hibernate: 
    
    drop table MY_SEQUENCES if exists
Hibernate: 
    
    create table Member (
       id bigint not null,
        name varchar(255) not null,
        primary key (id)
    )
Hibernate: 
    
    create table MY_SEQUENCES (
       sequence_name varchar(255) not null,
        next_val bigint,
        primary key (sequence_name)
    )
Hibernate: 
    
    insert into MY_SEQUENCES(sequence_name, next_val) values ('MEMBER_SEQ',0)
Hibernate: 
    select
        tbl.next_val 
    from
        MY_SEQUENCES tbl 
    where
        tbl.sequence_name=? for update
            
Hibernate: 
    update
        MY_SEQUENCES 
    set
        next_val=?  
    where
        next_val=? 
        and sequence_name=?
Hibernate: 
    /* insert hellojpa.Member
        */ insert 
        into
            Member
            (name, id) 
        values
            (?, ?)

8. @TableGenerator - 속성

1) 권장하는 식별자 전략

• 기본 키 제약 조건: null 아님, 유일, 변하면 안된다.
• 미래까지 이 조건을 만족하는 자연키는 찾기 어렵다. 대리키(대체키)를 사용하자. 
• 예를 들어 주민등록번호도 기본 키로 적절하기 않다. 
• 권장: Long형 + 대체키 + 키 생성전략 사용

 

 

출처 : 김영한, 자바 ORM 표준 JPA 프로그래밍 - 기본편

'JPA' 카테고리의 다른 글

단방향 연관관계  (0) 2022.07.01
요구사항 분석과 기본 매핑  (0) 2022.07.01
필드와 컬럼 맵핑  (0) 2022.06.30
엔티티 매핑  (0) 2022.06.30
영속성 컨텍스트  (0) 2022.06.29
복사했습니다!