Java Spring : DTO

김선미·2022년 6월 21일
0

DTO

  • DB에 연결된 클래스 대신 새로운 클래스를 대체하여 사용할 수 있는 라이브러리
  • CourseRequestDto.java 생성
@Setter
@Getter
@RequiredArgsConstructor
public class CourseRequestDto {
    private final String title;
    private final String tutor;
}
  • week02Application.java
# 기존 코드

//  Course new_course = new Course("웹개발의 봄, Spring", "임민영");
//  courseService.update(1L, new_course);

# Dto로 변경

    CourseRequestDto requestDto = new CourseRequestDto("웹개발의 봄, Spring", "임민영");
    courseService.update(1L, requestDto);
  • CourseService.java
    public Long update(Long id, CourseRequestDto requestDto) {
        Course course1 = courseRepository.findById(id).orElseThrow(
                () -> new IllegalArgumentException("해당 아이디가 존재하지 않습니다.")
        );
        course1.update(requestDto);
        return course1.getId();
    }
  • Course.java
    public void update(CourseRequestDto requestDto) {

# 기존 코드
//        this.title = course.title;
//        this.tutor = course.tutor;

# Dto로 변경
        this.title = requestDto.getTitle();
        this.tutor = requestDto.getTutor();
    }
}

더 알고싶은 점

  • DTO 사용해서 CourseService.java 변경할때 course1 은 원래 Course 클래스를 가져와서 쓴건지?
profile
백엔드 개발 공부

0개의 댓글