article thumbnail image
Published 2021. 6. 14. 23:35

 

DTO(Data Transfer Object)

 

프로세스 간에 데이터를 전달하는 객체

DAO, BO와의 차이점은 DTO에는 저장, 검색, 직렬화 및 역 직렬화를 제외하고 동작이 없다는 것

즉, DTO는 비즈니스 로직을 포함하지 않고 데이터를 전달하기 위한 단순한 객체

 

 

VO(Value Object)

 

Immutable 속성의 값을 가진 객체

자바에서 단순히 값을 표현하기 위해 불변 클래스를 만들어 사용한다.

 

 

DTO와 VO의 차이

 

참조(Reference)와 가변(Mutable)

 

class Money {
    private long amount;
    private Currency curr;

    public long getAmount() {
        return amount;
    }

    public void setAmount(long amount) {
        this.amount = amount;
    }

    public Currency getCurr() {
        return curr;
    }

    public void setCurr(Currency curr) {
        this.curr = curr;
    }

    @Override
    public String toString() {
        return this.amount + this.curr.getDesc();
    }
}

enum Currency {
    KRW("원"), DOLLAR("달러");

    private final String desc;

    Currency(String desc) {
        this.desc = desc;
    }

    public String getDesc() {
        return this.desc;
    }
}

 

일반적인 Money 클래스를 하나 작성해보자.

 

Money money = new Money();
money.setAmount(100);
money.setCurrency(Currency.KRW);

System.out.println(money.toString());

 

100원짜리 Money 객체를 만든다고 할 때, 객체를 생성한 후 setter를 통해 값을 넣어준다.

생성 된 Money 객체는 얼마든지 변경할 수 있다. amount 값이 100이 되었다가 200이 될 수도 있다.

이를 가변객체라고 부른다. Mutable Object

 

가변 객체는 참조 이동하기 때문에 개발자가 의도하지 않은 결과가 나타날 수 있다.

 

Money money1 = new Money();
money1.setAmount(100);
money1.setCurrency(Currency.KRW);

Money money2 = money1;
money2.setCurrency(Currency.DOLLAR);

System.out.println(money1);
System.out.println(money2);

 

위와 같은 코드를 작성했을 때

 

100원

100달러

 

와 같이 출력이 되길 원하지만 실제 결과는 그렇지 않다.

객체가 가지는 값이 주소값이기 때문에 money1, 2 는 같은 주소값을 바라보게 된다.

 

 

위와 같은 문제를 해결하기 위해  // 기본자료형과 같이 아예 복제를 해버리는 방법도 있지만 (참조가 아닌 복제) 

내부 값을 변경하지 못하는 불변객체 VO를 사용한다.

 

레퍼런스가 이동하는 것이 문제가 된다면 값의 변경을 막는 것이다.

 

class Money {
   private long amount;
   private Currency currency;

   public Money(long amount, Currency currency) {
      this.amount = amount;
      this.currency = currency;
   }

   public long getAmount() {
      return amount;
   }

   public Currency getCurrency() {
      return currency;
   }

   @Override
   public String toString() {
      return this.amount + this.currency.getDesc();
   }
}

 

값은 생성자를 통해서 받기 때문에 값을 변경하기 위해서는 새로운 객체를 만들어야한다.

내부 값을 변경하지 못하는 불변 객체 Immutable Object인 VO가 생성되는 것이다.

 

 

그런데 객체지향언어에서 객체란 상태, 행위를 가지고 있는 것인데 그 중 상태를 바꾸지 못하게 해도 되는 것일까?

 

예를 들면 '사람' 이라는 클래스로 '나'라는 객체를 생성했다고 가정하자. '나'는 상태가 변하게 된다.

그렇지만 나의 상태가 변한다고 해서 나를 새로 만들지는 않는다.

--> 가변 객체

 

500원짜리 동전을 생각해보자. 어떠한 상태에 의해 500원이 1000원이 되지는 않는다.

그저 500원은 500원인 것이고 100원짜리 객체를 가지고 싶다면 새로 생성해야한다.

--> 불변 객체

--> 상태 없이 값으로 취급하는 객체(Value Object)

 

 

DTO/VO의 차이는 아래 포스팅을 정리했습니다.

출처: https://multifrontgarden.tistory.com/182

 

 

 

 

DAO(Data Access Object)

 

실질적으로 DB에 접근하는 객체

효율적인 커넥션 관리

커넥션 생성, 로그인 정보 등 DB를 사용해 데이터를 조회하거나 조작하는 기능을 전담하여 메인 로직과 분리

mybatis와 같은 프레임워크를 사용하면 커넥션풀을 제공하기 때문에 DAO를 별도로 만드는 경우는 드물다.

 

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class TestDao {

    public void add(TestDto dto) 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,password) value(?,?,?)");


        preparedStatement.setString(1, dto.getName());
        preparedStatement.setInt(2, dto.getValue());
        preparedStatement.setString(3, dto.getData());
        preparedStatement.executeUpdate();
        preparedStatement.close();
        
        connection.close();

    }
}

 

 

복사했습니다!