Entity, DTO, VO
Aug 5, 2023
»
oop
Entity
Entity는 도메인 모델에서 식별 가능한 객체를 말한다. 일반적으로 고유한 식별자(ID)와 상태를 표현하는 속성을 가지고 있다. 식별자는 객체의 동일성을 보장하기 위해 사용된다. Entity의 속성이 변경되어도 식별자가 동일하다면 동일한 객체로 취급한다. 반대로, 모든 속성이 동일하더라도 식별자가 다르다면 서로 다른 객체로 취급한다. 따라서 Entity는 상태를 가질 수 있으며 이 상태는 변경될 수 있다. 도메인 모델에서 핵심적인 부분이라고 한다.
DTO(Data Transfer Object)
DTO는 계층 간 데이터 교환을 위한 객체이다. 주로 사용자 인터페이스와 비즈니스 로직 간, 또는 서버와 클라이언트 간의 데이터를 전달하는 용도로 사용된다. 어떠한 비즈니스 로직도 포함하고 있지 않으며 순수한 데이터 객체이다.
VO(Value Object)
VO는 값이나 속성을 표현하는 것으로 DTO와 달리 유일한 식별자를 가지지 않고 객체 내부의 속성들에 의해 정의(식별)되는 도메인 객체를 말한다. VO는 그 자체로 의미를 가지며, 일반적으로 불변성(Immutability)을 가지도록 설계한다. VO의 상태는 생성 시점에 설정되고 이후에는 변경되지 않아야 한다. 또한, 비즈니스 로직을 포함할 수 있다.
Entity, DTO, VO 예시
// Entity
public class Book {
private Long id; // Entity 식별자
private String title;
private Author author; // VO
public Book(Long id, String title, Author author) {
this.id = id;
this.title = title;
this.author = author;
}
public Long getId() {
return this.id;
}
public String getTitle() {
return this.title;
}
public Author getAuthor() {
return this.author;
}
}
// VO
public class Author {
private String firstName;
private String lastName;
public Author(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return this.firstName;
}
public String getLastName() {
return this.lastName;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Author author = (Author) o;
boolean isFirstNameEqual = Objects.equals(this.firstName, author.firstName);
boolean isLastNameEqual = Objects.equals(this.lastName, author.lastName);
return isFirstNameEqual && isLastNameEqual;
}
@Override
public int hashCode() {
return Objects.hash(this.firstName, this.lastName);
}
}
// DTO
public class BookResponse {
private Long id;
private String title;
private String author;
public BookResponse(Book book) {
this.id = book.getId();
this.title = book.getTitle();
this.author = book.getAuthor().getFirstName() + " " + book.getAuthor().getLastName();
}
}