자바를 사용하면서 왜 record를 사용해야하는지 알아보자
Database 엔티티를 그대로 반환하는 것은 굉장히 위험하다.
Database의 구성을 그대로 노출하기 때문이다.
이때 DTO는 Database 엔티티의 과노출(엔티티 전부를 노출하는 것)을 방지할 수 있다.
이제 왜 DTO를 만들때 자바 record를 써야하는지 알아보자
자바14에서 등장하고 16에서 안정화된 기능이다.
public class ProductDTO {
private Long id;
private String name;
private String description;
private double price;
public ProductDTO(Long id, String name, String description, double price) {
this.id = id;
this.name = name;
this.description = description;
this.price = price;
}
public Long getId() { return id; }
public String getName() { return name; }
public String getDescription() { return description; }
public double getPrice() { return price; }
}
recored사용한 DTO
public record ProductDTO(Long id, String name, String description, double price) {}
위처럼 간단하게 사용할 수 있다.
DTO를 사용할땐 자바 record를 사용하도록 하자
하지만 커스텀 메서드를 지정하거나 뭔가 개인화작업이 필요한경우 class가 더 도움이 되는 경우도 있다.