Spring/Spring Boot

[Spring] 07. DTO를 사용하는 이유 - Data Transfer Object

민돌v 2021. 11. 11. 21:12
728x90

스프링 프레임워크의 구조 (출처 : https://intro0517.tistory.com/151)

 

1. DTO란?

DTO(Data Transfer Object)란 계층간 데이터 교환을 위해 사용하는 객체(Java Beans)입니다. 

 

DTO를 사용하는 이유는, 자바 domain 객체를 바로 접근하지 않기 위해서 입니다.

고로! 가볍게 생각헤서, 테이블을 조작하기 위해 한단계더 거쳐가는 완충제라고 생각하면 됩니다.

 

✅ 테이블을 직접적으로 접근하지 않음으로써, 데이터를 보호하기 위함

 

생성하기

  1. src > main > java > com.sparta.item01 > dto 패키지 생성
  2. src > main > java > com.sparta.item01 > dto 에 LectureRequestDto 파일 생성 

 

  1. LectureRequestDto.java
@NoArgsConstructor
@Getter
public class LectureRequestDto {
    private String title;
    private String tutor;

    public LectureRequestDto(String title, String tutor) {
        this.title = title;
        this.tutor = tutor;
    }
}

 

LectureService

@Getter
@NoArgsConstructor
@Entity
public class Course extends Timestamped {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(nullable = false)
    private String title;

    @Column(nullable = false)
    private String tutor;

    public Course(String title, String tutor) {
        this.title = title;
        this.tutor = tutor;
    }

    public void update(LectureRequestDto requestDto) {
        this.title = requestDto.getTitle();
        this.tutor = requestDto.getTutor();
    }
}

 

Lecture update 변경

@Getter
@NoArgsConstructor
@Entity
public class Course extends Timestamped {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(nullable = false)
    private String title;

    @Column(nullable = false)
    private String tutor;

    public Course(String title, String tutor) {
        this.title = title;
        this.tutor = tutor;
    }

    public void update(LectureRequestDto requestDto) {
        this.title = requestDto.getTitle();
        this.tutor = requestDto.getTutor();
    }
}

 

이런식으로  Lecture 테이블을 직접 생성해서 접근하기 보다, DTO라는 완충제를 이용해 사용한다.

반응형