티스토리 뷰


JPA를 사용할 때, 엔티티의 날짜에서 자바는 보통 java.util.Date 객체를 사용합니다.


하지만, DB에는 날짜도 여러 형태가 존재합니다.

예를 들어, date(년월일), time(시분초), timestamp(년월일 시분초) 또는 datetime 으로 세가지의 타입이 존재합니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.util.Date;
import lombok.Data;
import javax.persistence.*;
 
@Entity
@Data
public class Article {
    
    @Id
    @GeneratedValue
    int id;
    String subject;
    
    @Column(length = 100000000)
    String content;
    
    @Temporal(TemporalType.DATE)
    Date regDate;
    @Temporal(TemporalType.TIME)
    Date regTime;
    @Temporal(TemporalType.TIMESTAMP)
    Date regTimestamp;
}
 
cs


위에 예제를 간단히 살펴 보면, 자바에서는 모두 Date 객체 이지만, @Temporal이라는 애노테이션을 사용하여, DB 타입에 맞도록 매핑할 수 있습니다.


TemporalType.Date : 년-월-일 의 date 타입

TemporalType.Time : 시:분:초 의  time 타입

TemporalType.TIMESTAMP : date + time 의 timestamp(datetime) 타입


애노테이션을 사용하지 않을 경우 기본값은 timestamp 입니다.


JPA 데이터베이스 방언에 의해, 데이터베이스의 타입에 따른 timestamp 또는 datetime은 자동으로 작성됩니다.


댓글