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();
}
}
}
이와 같이 컨버터를 설정해주면 된다.
'개발 > 기타개발' 카테고리의 다른 글
RESTFul Api 3장 HTTP를 이용한 인터랙션 설계 (0) | 2019.03.05 |
---|---|
RESTFul Api 2장 URI 식별자 설계 (0) | 2019.03.03 |
SSL 인증방식 그리고 handshake (0) | 2019.02.27 |
RESTFul Api 1장 REST 소개 (0) | 2019.02.26 |
자바 ORM 표준 JPA 소개 (0) | 2019.01.06 |
댓글