Written by coh at home
[Spring] View의 날짜 정보를 엔티티로 본문
View에서 DTO로 데이터를 넘기거나 Parameter로 넘길 때 Controller에서 String 타입으로 받게 된다.
그래서 개인적으로 나는 View에서는 DTO를 쓰고 해당 DTO를 Entity로 만드는 것이 좋다.
오늘 할 주제는 넘어온 String 데이터를 LocalDateTime / LocalDate 형식으로 바꾸는 방법이다.
DTO에 넘어오는 캘린더 값은 "2024-05-25" 형식의 데이터가 넘어오게 된다.
String -> LocalDateTime
public static ProductOrder toEntity(OrderDTO orderDTO, Member member, ShopProduct shopProduct, ShopConnection shopConnection) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime time = LocalDateTime.parse(orderDTO.getInsertDateTime() + " 00:00:00", formatter);
ProductOrder productOrder = ProductOrder.builder()
.member(member)
.shopProduct(shopProduct)
.shopConnection(shopConnection) //------- 관련 엔티티 설정
.orderName(orderDTO.getSellerProductName())
.buyProductCount(orderDTO.getBuyProductCount())
.salePrice(orderDTO.getSalePrice())
.totalPrice(orderDTO.getTotalPrice())
.status(DeliveryStatus.READY)
.address(orderDTO.getAddress())
.customId(orderDTO.getCustomId())
.customMemo(orderDTO.getMemo())
.phoneNumber(orderDTO.getPhoneNumber())
.addressDetail(orderDTO.getAddressDetail())
.zipCode(orderDTO.getZipCode())
.orderId(orderDTO.getOrderId())
.build();
productOrder.setInsertDateTime(time);
return productOrder;
}
보면은 DTO를 빌더패턴으로 엔터티로 만드는 코드이다. 주목해야하는 것은 위에 있는 Formatter이다.
LocalDateTime 은 기본적으로 "yyyy-MM-dd HH:mm:ss" 형식의 데이터를 가지므로 이런 형식으로 데이터를 만들겠다고 지정해주는 것이다.
String -> LocalDate
LocalDate는 형식에 시간을 포함하지 않는다. 따라서 바로 저장이 가능하다.
LocalDate date = LocalDate.parse(orderDTO.getInsertDateTime());
LocalDate은 기본적으로 "yyyy-MM-dd" 형식이기 때문에 현재 들어온 데이터와 일치하므로 바로 이렇게 저장이 가능하다.
'Advanced > Spring' 카테고리의 다른 글
[SPRING] (0) | 2023.09.12 |
---|---|
[SPRING] Web server failed to start. Port 8080 was already in use. (0) | 2023.09.04 |