본문 바로가기
  • Where there is a will there is a way.
개발/기타개발

JPA java8 localDate 변환구현 ( 컨버터 )

by 소확행개발자 2019. 2. 28.

JPA 에서 Model로 데이터를 전환할 때

여기서 고려해야 할 상황은 

현 DB가 


String 으로 "2018-10-12" 이렇게 설정되어 있거나

"" 으로 빈 데이터값을 표현하고 있다는 거다.


@Entity
@Table(name = "test")
public class Test implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(updatable = false, name = "idx")
private Integer id;

]
@Column(name = "start_date")
@Convert(converter = LocalDateTimeAttributeConverter.class)
private LocalDateTime startDate;
@Column(name = "end_date")
@Convert(converter = LocalDateTimeAttributeConverter.class)
private LocalDateTime endDate;



}


물론 그렇게 짜면 좋지 않다.


timestamp로 저장될 때 지역의 정보도 가지고 있다거나 최소한 Date 형식은 맞춰져 있으면 좋겠다.




사용법은 간단하다. 위와 같이

LocalDateTime을 vachar 로 정의된 디비와 매핑시켜 준다.


그런 다음에


@Converter
public class LocalDateTimeAttributeConverter implements AttributeConverter<LocalDateTime, String> {


@Override
public String convertToDatabaseColumn(LocalDateTime attribute) {

if(attribute == null) {
return "";
} else {
return attribute.toLocalDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
}
}


@Override
public LocalDateTime convertToEntityAttribute(String dbData) {

if(StringUtil.isNullOrEmpty(dbData)) {
return null;
} else {
return LocalDate.parse(dbData, DateTimeFormatter.ISO_LOCAL_DATE).atStartOfDay();
}
}
}


이와 같이 컨버터를 설정해주면 된다.

댓글