우노
[Kotlin] DTO와 Entity의 관계 본문
DTO와 Entity의 관계
- DTO(Data Transfer Object)와 Entity는 역할과 사용 목적이 다르며,
- 이로 인해 서로 명확히 구분해서 사용됩니다.
DTO와 Entity의 차이
항목 | DTO | Entity |
---|---|---|
역할 | 데이터 전송에 사용되는 객체 | 데이터베이스와 직접 연결된 객체 |
목적 | 클라이언트-서버 간 데이터 교환 간소화 | 데이터베이스 테이블의 구조를 반영 |
속성 | 필요한 데이터만 포함, 가공된 데이터 가능 | 데이터베이스의 컬럼에 직접 매핑되는 필드 포함 |
위치 | 주로 API 요청/응답에서 사용됨 | 서비스 내부에서 사용됨 |
종속성 | 독립적, 데이터베이스와 무관 | 데이터베이스와 밀접하게 연관 |
DTO → Entity
- 필수는 아닙니다.
- 단순 조회만 수행하는 경우에는 DTO를 Entity로 변환할 필요가 없습니다.
- 하지만, DTO 데이터를 기반으로 데이터베이스 저장, 수정, 삭제 작업을 진행하는 경우에는 필수입니다.
Entity → DTO
- 필수는 아닙니다.
- 하지만, Entity를 그대로 사용한다면 클라이언트에게 불필요한 데이터가 노출되거나
- 스키마 변경 시 유지보수성에 어려움이 있을 수 있습니다.
변환 예제 - ModelMapper 사용
- ModelMapper는 DTO와 Entity 간의 변환을 쉽게 해주는 Java 라이브러리입니다.
- 객체 간의 매핑 작업을 자동화하고, 복잡한 변환을 간단하게 처리할 수 있게 도와줍니다.
ModelMapper
를 사용하여User
Entity를UserDTO
로 변환하는 예제를 확인해보겠습니다.
User Entity
public class User {
private Long id;
private String name;
private String email;
// Constructor, getters and setters
}
UserDTO
public class UserDTO {
private Long id;
private String name;
private String email;
// Constructor, getters and setters
}
ModelMapper를 사용한 변환
import org.modelmapper.ModelMapper;
public class ModelMapperExample {
public static void main(String[] args) {
// ModelMapper 객체 생성
ModelMapper modelMapper = new ModelMapper();
// Entity 객체 생성
User user = new User();
user.setId(1L);
user.setName("John Doe");
user.setEmail("john.doe@example.com");
// Entity -> DTO 변환
UserDTO userDTO = modelMapper.map(user, UserDTO.class);
// 결과 출력
System.out.println("UserDTO ID: " + userDTO.getId());
System.out.println("UserDTO Name: " + userDTO.getName());
System.out.println("UserDTO Email: " + userDTO.getEmail());
}
}
결론
- DTO ↔ Entity 변환은 필수가 아니지만, 보안, 유지보수, 유연성을 위해 권장됩니다.
'Web_App > Kotlin' 카테고리의 다른 글
[Kotlin] Controller와 Service의 계층 구조 (0) | 2024.12.20 |
---|---|
[Kotlin] @SqlResultSetMapping (0) | 2024.12.20 |
[Kotlin] ORM, JPA, Spring Data JPA (1) | 2024.12.18 |
[Kotlin] @Entity와 @Repository (0) | 2024.12.18 |
[Kotlin] @Scheduled 란? (0) | 2024.12.02 |
Comments