728x90
  • 직접 할당

@Id 설정 대상에 직접 값 설정

저장하기 전에 생성자를 할당한다, 보통 생성 시점에 전달

@Entity
@Table(name = "user1")
public class User1{
    @Id
    private String name;
    private String email;
    
    protected User() {}
    
    public User (String name, String email){
    	this.name = name;
        this.email = email;
	}
}

이렇게 가장 단순한 방법으로 생성하는 방식이다.

  • 식별 칼럼 방식

칼럼 중에 auto_increment 같이 객체 생성시에 식별값을 설정하지 않는 경우가 있다.

그럴 때에는 설정을 추가하여 persist()를 실행할 때 객체에 식별자 값을 할당하게 할 수 있다.

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class User2{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    
    protected User2(){}

    public User2(Long id, String name) {
        this.id = id;
        this.name = name;
    }
}

그 외에도 몇가지 방식이 더 있지만 많이 사용하지 않기 때문에 이렇게만 알아보도록 하겠다.

'백엔드 > JPA' 카테고리의 다른 글

JPA 7장 (Set collection mapping)  (0) 2023.03.18
JPA 6장 (@Embeddable)  (0) 2023.03.17
JPA 4장 (Entity에 대하여)  (0) 2023.03.16
JPA 3장 (간단한 CRUD 구현해보기)  (0) 2023.03.16
JPA 2장 (영속 컨텍스트)  (0) 2023.03.15

+ Recent posts