[Spring] DTO와 Entity

ma0·2024년 9월 11일

JSP

목록 보기
7/7

DTO - 계층 간 데이터 전송 위한 객체

  • 클라이언트-서버 / 서비스 계층-프레젠테이션 계층 간 데이터 전송
  • 데이터 전달 목적으로만 사용, 데이터베이스와 직접 연결 x
  • Enity에서 일부 필요한 필드만을 담거나, 여러 Entity 데이터를 합쳐 클라이언트에 전달하는 역할

Entity - 데이터베이스 테이블과 직접적으로 매핑되는 클래스

  • 데이터가 저장되는 영속적 객체(POJO, Plain Old JAVA Object)
  • 데이터베이스 상의 데이터 읽기/쓰기 작업 처리


1. DTO → Entity 변환

= 클라이언트로부터 받은 데이터를 DTO로 처리 후, Entity로 변환하여 DB에 저장

=> 직접적으로 Entity에 매핑하지 않고, DTO 거쳐 필요한 검증 + 추가 처리 수행 후 저장 가능
=> Lombok 설치 시 편하게 Getter, Setter, ToString 실행 가능

// DTO 클래스 (Friend DTO)
public class FriendDTO {
    private String username;
    private Integer age;
    private String phone;
    private LocalDate birthday;
    private Boolean active;

    // Getter/Setter 및 생성자 생략
}

// DTO → Entity 변환
public FriendEntity dtoToEntity(FriendDTO dto) {
    FriendEntity entity = new FriendEntity();
    entity.setUsername(dto.getUsername());
    entity.setAge(dto.getAge());
    entity.setPhone(dto.getPhone());
    entity.setBirthday(dto.getBirthday());
    entity.setActive(dto.getActive());
    return entity;

2. Entity → DTO 변환

=> Entity를 직접 클라이언트에 노출하는 것은 보안/유지 보수 문제를 일으킬 수 있으므로, DTO로 변환하여 필요한 정보만을 클라이언트에게 전달

// Entity 클래스 (Friend 엔티티)
@Entity
@Table(name = "friends")
public class FriendEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String username;
    private Integer age;
    private String phone;
    private LocalDate birthday;
    private Boolean active;

    // Getter/Setter 및 생성자 생략
}
// Entity → DTO 변환
public FriendDTO entityToDTO(FriendEntity entity) {
    FriendDTO dto = new FriendDTO();
    dto.setUsername(entity.getUsername());
    dto.setAge(entity.getAge());
    dto.setPhone(entity.getPhone());
    dto.setBirthday(entity.getBirthday());
    dto.setActive(entity.getActive());
    return dto;
}


3. DTO, Entity를 분리해야 하는 이유

1. 보안 문제 방지

2. 유지 보수성 향상

: 비즈니스 로직 / 데이터 전송 분리함으로써, Entity의 변경이 클라이언트와 데이터 전송 방식에 영향을 미치지 않게 할 수 있음
=> DB Skima , Entity 구조가 바뀌어도 DTO를 통해 DB 통신 구조 유지 가능

3. 데이터 최적화

: 많은 정보를 가진 Entity와 달리 DTO는 클라이언트에게 필요한 데이터만 전송

4. 응답 성능 개선

: DTO 사용 시 필요 데이터만 전송함으로써 네트워크 트래픽 감소, 성능 최적화



4. Builder를 사용한 변환

Builder 패턴

= 객체를 단계적으로 생성하기 위해 설계된 패턴

1. 객체 생성의 가독성 향상 : 메서드 체이닝 사용해 객체를 단계별로 생성할 수 있도록 해 줌

2. 복잡한 객체 생성의 단계적 처리 : 여러 필드를 단계적으로 설정할 수 있어, 선택적 필드 설정이나 복잡한 객체 생성 시 유용
=> 필요한 필드만 지정 가능

3. 불변성 유지 : 생성자는 private으로 감추고, Builder가 객체 생성을 책임지므로 외부에서 객체 수정 불가능

4. 복잡한 객체의 유연한 생성 : 상황에 따라 필요한 필드만 선택할 수 있어 DTO와 Entity 클래스에 많이 활용

5. 객체 일관성 보장 : Builder 내부에서 객체 상태 체크, 객체 완성 시점에 일관성 검사 가능

DTO → Entity 변환

  • 친구 목록 CRUD 만들기 게시글 참조
public static Friend toDTO(FriendEntity friendEntity){
	return Friend.Builder()
    		.fseq(friendEntity.getFseq())
            .fname(friendEntity.getFname())
			.age(friendEntity.getAge())
			.phone(friendEntity.getPhone())
			.birthday(friendEntity.getBirthday())
			.active(friendEntity.isActive())
			.build();
}

Entity → DTO 변환

public static FriendEntity toEntity(Friend friend) {
		return FriendEntity.builder()
				.fseq(friend.getFseq())
				.fname(friend.getFname())
				.age(friend.getAge())
				.phone(friend.getPhone())
				.birthday(friend.getBirthday())
				.active(friend.isActive())
				.build();
	}
profile
우당탕탕 개발 간잽 일기 - 간잽이 수백 번이면 전문가일지도?

0개의 댓글