DTO - 계층 간 데이터 전송 위한 객체
- 클라이언트-서버 / 서비스 계층-프레젠테이션 계층 간 데이터 전송
- 데이터 전달 목적으로만 사용, 데이터베이스와 직접 연결 x
- Enity에서 일부 필요한 필드만을 담거나, 여러 Entity 데이터를 합쳐 클라이언트에 전달하는 역할
Entity - 데이터베이스 테이블과 직접적으로 매핑되는 클래스
- 데이터가 저장되는 영속적 객체(POJO, Plain Old JAVA Object)
- 데이터베이스 상의 데이터 읽기/쓰기 작업 처리

=> 직접적으로 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;
=> 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;
}
: 비즈니스 로직 / 데이터 전송 분리함으로써, Entity의 변경이 클라이언트와 데이터 전송 방식에 영향을 미치지 않게 할 수 있음
=> DB Skima , Entity 구조가 바뀌어도 DTO를 통해 DB 통신 구조 유지 가능
: 많은 정보를 가진 Entity와 달리 DTO는 클라이언트에게 필요한 데이터만 전송
: DTO 사용 시 필요 데이터만 전송함으로써 네트워크 트래픽 감소, 성능 최적화
Builder 패턴
= 객체를 단계적으로 생성하기 위해 설계된 패턴
1. 객체 생성의 가독성 향상 : 메서드 체이닝 사용해 객체를 단계별로 생성할 수 있도록 해 줌
2. 복잡한 객체 생성의 단계적 처리 : 여러 필드를 단계적으로 설정할 수 있어, 선택적 필드 설정이나 복잡한 객체 생성 시 유용
=> 필요한 필드만 지정 가능
3. 불변성 유지 : 생성자는 private으로 감추고, Builder가 객체 생성을 책임지므로 외부에서 객체 수정 불가능
4. 복잡한 객체의 유연한 생성 : 상황에 따라 필요한 필드만 선택할 수 있어 DTO와 Entity 클래스에 많이 활용
5. 객체 일관성 보장 : Builder 내부에서 객체 상태 체크, 객체 완성 시점에 일관성 검사 가능
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();
}
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();
}