Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | |
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 | 31 |
Tags
- 자료구조
- github
- wil
- 메서드
- Spring
- 자바
- 이진 탐색(binary search)
- 항해99
- HTML
- 코딩테스트 준비
- Grafana
- 코딩공부
- css
- 99클럽
- 회고
- 코딩문제
- 정렬 알고리즘(sort algorithm)
- 면접(java
- aop
- 우선순위 큐(priorityqueue)
- cs 공부)준비
- 프로그래머스
- GIT
- Entity
- Til
- ArrayList
- 배열
- Java
- 개발자 취업
- 코딩
Archives
- Today
- Total
hayu's 개발 일지
[TIL]240326 Dto의 toEntity 본문
toEntity 란?
- toEntity는 Dto에서 엔티티 객체로 변환하는 메서드이다.
- Spring에서는 요청을 DTO형태로 받아 엔티티 객체로 변환하여 데이터 베이스에 저장하거나 업데이트할 때 toEntity를 사용된다.
@Getter
public static class CreateReviewRequestDto {
@NotBlank(message = "리뷰를 입력해주세요.")
private String contents;
@PositiveOrZero(message = "별점을 입력해주세요.")
private int rating;
public Review toEntity(Member member, Product product) {
return Review.builder()
.contents(this.contents)
.rating(this.rating)
.member(member)
.product(product)
.build();
}
}
- toEntity를 사용하면 서비스에서 코드가 간결해진다.
@Transactional
public CreateReviewResponseDto createReview(Long productId, String email, CreateReviewRequestDto reviewRequestDto) {
Member member = memberRepository.findByEmail(email)
.orElseThrow(() -> new BadRequestException(ErrorCode.NOT_FOUND_MEMBER_EMAIL.getMessage()));
Product product = productRepository.findById(productId)
.orElseThrow(() -> new BadRequestException(ErrorCode.NOT_FOUND_PRODUCT.getMessage()));
Review review = reviewRepository.save(reviewRequestDto.toEntity(member, product));
return new CreateReviewResponseDto(review);
}
'프레임워크 > spring' 카테고리의 다른 글
[TIL]240402 Polling, Long Polling, Websocket, SSE (0) | 2024.04.02 |
---|---|
[TIL]240401 Websocket(웹소켓) (0) | 2024.04.01 |
[TIL]240321 엔티티(Entity) 연관관계 매핑(2) (0) | 2024.03.21 |
[TIL]240320 엔티티(Entity) 연관관계 매핑(1) (0) | 2024.03.20 |
[TIL]240319 Entity & DTO (0) | 2024.03.19 |