2020 12 07
DTO ,DAO VO 뭐 이런 말들은 많이 들어는 봤지만 정확히 어떤 역할을 하는지는 잘 모르고 있다. 객체지향을 설계할 때나 데이터를 전달할 때 이런 말은 많이 쓰고 있는 것 같다. 이 용어들의 정의나 역할은 무엇인지, 또 어떨 때 사용되는지, 어떤 차이점들이 있는지 한 번 알아보자.
데이터 전송 객체(Data Transfer Object) 는 프로세스 간에 데이터를 전달하는 객체이다.
위에 말들은 너무 어렵고 이해가 잘 안가서 코드로 다시 살펴보았다
public class User{
@Column(nullable = false)
private int userId;
private String name;
@Builder
public User(int userId, String name){
this.userId = userId;
this.name = name;
}
public int getId(){
return userId;
}
public int getName(){
return name;
}
}
이렇게 객체로 유저를 만들어서 데이터베이스에 있는 내용을 객체로 만든다는 것을 DTO라고 볼 수 있다. 여러 블로그들에서 setter도 DTO에 넣는 것을 볼 수 있었는데, 그렇게 짜는 것 보다, 따로 Controller Layer에서 Response DTO 형태로 전달하는 것이 좋을 것 같다.
VO(Value Object) 는 값 객체이다.
VO도 Getter 와 Setter를 가질 수 있으며, 값 끼리 비교를 할 때, 값 안에 있는 모든 Attribute를 비교한다.
...
public boolean equals(Object o){
if(this == o) return true;
if(o == null || ...)return false
...
데이터 접근 객체(Data Access Object)는 일부 데이터베이스나 기타 Persistence 매커니즘에 추상 인터페이스를 제공하는 객체이다.
웹서버는 DB와 연결하기 위해서 계속 Connection 객체를 생성하는데, 이렇게 된다면 DB에 연결하기 위해 많은 자원이 사용될 수밖에 없다. 그래서 Connection Pool 이라는 것을 사용한다. 먼저 Connection을 만들어 놓고, 필요할 때마다 가져다 쓰는 것이다.
하지만 유저 한 명이 접속해서 하나의 커넥션만 만드는게 아니라, 글쓰기, 읽기 마다 각각 만드는 것도 엄청나게 많은 커넥션이 일어난다.
따라서 Database에 접속하는 객체를 한 개만 만들고, 모든 페이지에서 이 객체로 일을 처리한다는 것이 바로 DAO 이다. 자바 코드로 한 번 살펴보자.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class DAO {
public void add(User user) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "root");
PreparedStatement preparedStatement = connection.prepareStatement("insert into users(id,name) value(?,?)");
preparedStatement.setInt(1, user.getUserId());
preparedStatement.setString(2, user.getName());
preparedStatement.executeUpdate();
preparedStatement.close();
connection.close();
}
}