본문 바로가기
Spring/TroubleShooting

Sqlite LocalDateTime 적용 문제

by Mecodata 2024. 2. 19.

문제

MySQL과 다르게 Sqlite는 Spring Data JPA를 통해 LocalDateTime을 적용하여 Entity 혹은 DTO의 필드(컬럼)를 정의하면 날짜 데이터가 아닌 알아보기 힘든 숫자 형식으로 데이터가 DB에 저장됨

해결 방법

LocalDateTime 데이터를 DateTimeFormatter를 이용하여 String으로 변환하여 저장

public class carDTO {

    @Column(columnDefinition = "text", updatable = false)
    private String createdDateTime;

    @Column(columnDefinition = "text")
    private String modifiedDateTime;

    @PrePersist
    protected void onCreate() {
        createdDateTime = this.LocalDateTimeToString(LocalDateTime.now());
    }

    @PreUpdate
    protected void onUpdate() {
        modifiedDateTime = this.LocalDateTimeToString(LocalDateTime.now());
    }
    
    public static String LocalDateTimeToString(LocalDateTime localDateTime) {
        return localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }
	
}

댓글