Entity와 DTO의 차이가 무엇이고, 분리해야 하는 이유에 대해 정리해 보고자 한다.
Entity는 데티어베이스의 테이블과 직접적으로 매핑되는 클래스이다. 주로 ORM(Object-Relational Mapping) 프레임워크를 통해 사용되며, Java에서는 JPA(Java Persistence API)가 널리 사용된다. Entity는 데이터베이스의 상태를 반영하고, 영속성(Persistence)을 가지고 있다.
@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    private String username;
    private String password;
    private String email;
    // Getters and setters
}
DTO는 데이터 전송을 목적으로 사용하는 객체이다. 주로 네트워크를 통해 데이터를 전송할 때, 또는 레이어 간의 데이터 교환을 위해 사용된다. DTO는 데이터베이스와 직접적인 연관이 없으며, 영속성을 가지지 않는다.
public class UserDTO {
    private Long id;
    private String username;
    private String email;
    // Getters and setters
}
Entity와 DTO를 분리하는 이유는 다음과 같은 이유들이 있다:
// Entity에 비밀번호와 같은 민감한 정보 포함
@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String username;
    private String password; // 민감한 정보
    private String email;
    // Getters and setters
}
// DTO에는 민감한 정보 제외
public class UserDTO {
    private Long id;
    private String username;
    private String email;
    // Getters and setters
}
// Entity의 모든 필드 전송 시 성능 저하 가능성
@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String description;
    private BigDecimal price;
    private LocalDateTime createdDate;
    // Getters and setters
}
// DTO를 통해 필요한 필드만 전송
public class ProductDTO {
    private Long id;
    private String name;
    private BigDecimal price;
    // Getters and setters
}
Entity와 DTO는 각각 다른 목적을 가지고 있으며, 그 목적에 맞게 사용해야 한다. Entity는 데이터베이스와의 상호작용을 관리하고, DTO는 데이터를 전송하는 데 최적화되어 있다. 이 둘을 적절히 사용하면 소프트웨어의 유지보수성과 성능을 향상시킬 수 있다.
참조