[Java] DAO, DTO

nana·2024년 8월 11일
0

JAVA

목록 보기
5/5

Java에서 DAO(Data Access Object)와 DTO(Data Transfer Object)는 데이터베이스와 애플리케이션 사이의 데이터 전송을 담당하는 패턴이다.

이 두 가지는 보통 함께 사용되며, 서로 다른 역할을 한다.

DAO / DAO 구조를 사용하면 애플리케이션의 유지보수성과 확장성이 높아진다는 장점이 있다.

DAO는 데이터베이스 로직을 캡슐화하여 재사용성을 높이고, DTO는 계층 간 데이터 전송을 단순화해준다.

1. DAO (Data Access Object)

DAO는 Database와 상호작용을 담당하는 객체이다.

프로젝트의 서비스 모델에 해당하는 부분과 데이터베이스를 연결하는 역할을 하며,

데이터의 CRUD 작업을 시행하는 클래스이다. 데이터베이스 접근 로직을 포함하며 SQL 쿼리를 실행하고 결과를 반환한다.

예시

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDAO {
    private Connection connection;

    public UserDAO(Connection connection) {
        this.connection = connection;
    }

    // Create
    public void createUser(UserDTO user) throws SQLException {
        String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setString(1, user.getName());
            pstmt.setString(2, user.getEmail());
            pstmt.executeUpdate();
        }
    }

    // Read
    public UserDTO getUserById(int id) throws SQLException {
        String sql = "SELECT * FROM users WHERE id = ?";
        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setInt(1, id);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    return new UserDTO(rs.getInt("id"), rs.getString("name"), rs.getString("email"));
                }
            }
        }
        return null;
    }

    // Update
    public void updateUser(UserDTO user) throws SQLException {
        String sql = "UPDATE users SET name = ?, email = ? WHERE id = ?";
        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setString(1, user.getName());
            pstmt.setString(2, user.getEmail());
            pstmt.setInt(3, user.getId());
            pstmt.executeUpdate();
        }
    }

    // Delete
    public void deleteUser(int id) throws SQLException {
        String sql = "DELETE FROM users WHERE id = ?";
        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setInt(1, id);
            pstmt.executeUpdate();
        }
    }

    // All users retrieval
    public List<UserDTO> getAllUsers() throws SQLException {
        List<UserDTO> users = new ArrayList<>();
        String sql = "SELECT * FROM users";
        try (PreparedStatement pstmt = connection.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {
            while (rs.next()) {
                users.add(new UserDTO(rs.getInt("id"), rs.getString("name"), rs.getString("email")));
            }
        }
        return users;
    }
}

2. DTO (Data Transfer Object)

DTO는 계층 간 데이터 전송을 담당하는 객체이다.

DTO는 보통 서비스 또는 컨트롤러 간 데이터를 주고받기 위해 사용되기 때문에 로직을 가지지 않으며, 따라서 getter / setter로만 이루어진 클래스이다.

주로 데이터베이스의 한 레코드에 해당하는 필드를 가지고 있으며, 데이터의 구조만을 표현하고 비즈니스 로직은 포함하지 않는다.

예시

public class UserDTO {
    private int id;
    private String name;
    private String email;

    public UserDTO() {}

    public UserDTO(int id, String name, String email) {
        this.id = id;
        this.name = name;
        this.email = email;
    }

    // Getter와 Setter
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}
profile
프론트엔드 개발자 도전기

0개의 댓글