Reference. 한 번에 끝내는 Java/Spring 웹 개발 마스터 초격차 패키지 Online
이전 글
1. Entity Annotation
- @Entity: JPA에서 관리하는 도메인이라는 것을 설정
- @Id: PK역할을 하며 필수조건
- @GeneratedValue:
- 어노테이션 안에GenerationType strategy() default AUTO;
중요
- 트랜잭션이 종료되기 전, autoIncrese를 통해 아이디 값을 사전에 가져온다. commit 되지 않고, 로직이 종료되어도 키는 증가된다.
1. IDENTITY:Mysql, Mariadb
2. SEQUENCE:Oracle, Postgre, h2
3. TABLE: DB에 상관없이 ID를 관리하는 별도에 테이블을 사용
4. AUTO: default, 각 DB에 적합한 값을 전달 (DB의 의존성이 필요 없음)
- @Table: 테이블 관련 name, catalog, schema, uniqueConstraints, indexes 설정
- name: 특이사항에 적용 도메인과 테이블은 동일이 원칙
- indexes: DB 컬럼에 인덱스 생성 (일반적 사용X, DB에서 직접 설정)
- uniqueConstraints: DB 컬럼에 제약조건 설정 (일반적 사용X, DB에서 직접 설정)
@Table(name="user_lagacy", indexes = {@Index(columnList = "name")}, uniqueConstraints = {@UniqueConstraint(columnNames = "email")})
Hibernate:
create table user_lagacy (
id bigint not null,
created_at timestamp,
email varchar(255),
name varchar(255),
updated_at timestamp,
primary key (id)
)
Hibernate: create index IDXgj2fy3dcix7ph7k8684gka40c on user (name)
Hibernate:
alter table user
add constraint UKob8kqyqqgmefl0aco34akdtpe unique (email)
- @Colum: 각 컬럼에 속성을 지정
- name: 컬럼에 이름을 별도로 지정
- nullable: DDL 쿼리를 생성을 할 때, null 속성을 지정 (validation X)
- unique: 컬럼에 unique 속성을 지정
- length: varchar에 사이즈가 default 255, 사이즈를 변경할 수 있음
@Column(length = 500)
private String email;
@Column(name="reg_at", nullable = false, unique = true)
private LocalDateTime createdAt;
Hibernate:
create table user (
id bigint not null,
reg_at timestamp not null,
email varchar(500),
name varchar(255),
updated_at timestamp,
primary key (id)
)
Hibernate:
alter table user
add constraint UK_meybv2hnaajcag242r0bvhh5 unique (reg_at)
- insertable: insert 할 때 저장할지 안할지 지정 (default: true)
- updatable: update 할 때 저장할지 안할지 지정 (default: true)
@Column(updatable = false)
private LocalDateTime createdAt;
@Column(insertable = false)
private LocalDateTime updatedAt;
<insert>
Hibernate:
insert
into
user
(created_at, email, name, id)
values
(?, ?, ?, ?)
<update>
Hibernate:
update
user
set
email=?,
name=?,
updated_at=?
where
id=
- @Transient: 객체에서 사용할 속성으로만 지정, 영속성 처리에서 제외(DB반영 X)
- @Enumerated: Enum 클래스를 사용하는 경우 지정 [ default: ORDINAL(순서) ]
→ Enum에 속성이 추가되는 경우 ORDINAL값이 바뀔 수 있음, 잠재적 버그 발생
→ Enum 사용시 EnumType.STRING을 사용
public enum Gender {
MALE, (ORDINAL: 0)
FEMALE (ORDINAL: 1)
}
@Target({METHOD, FIELD})
@Retention(RUNTIME)
public @interface Enumerated {
/** (Optional) The type used in mapping an enum type. */
EnumType value() default ORDINAL;
}
public enum EnumType {
/** Persist enumerated type property or field as an integer. */
ORDINAL,
/** Persist enumerated type property or field as a string. */
STRING
}
Enum 속성에 따른 결과 값
@Enumerated(value = EnumType.STRING)
private Gender gender;
<EnumType.ORDINAL>
Hibernate:
select
*
from
user limit 1;
result : 0
<EnumType.STRING>
Hibernate:
select
*
from
user limit 1;
result : MALE
'백엔드 > JPA' 카테고리의 다른 글
[ JPA ] 5-2. Entity Relations ( 1:1 @OneToOne ) (0) | 2021.07.25 |
---|---|
[ JPA ] 5-1. Entity Relations (ERD, 데이터베이스 기준 연관 관계) (0) | 2021.07.25 |
[ JPA ] 4. Entity Listener (1) | 2021.07.24 |
[ JPA ] 2. Query Method 정의 및 실습 (0) | 2021.07.21 |
[ JPA ] 1. Repository interface 메소드 (1) | 2021.07.20 |