๐ DTO, DAO ์ ๋ฆฌ ๐
Data Transfer Object
๋ฐ์ดํฐ ์ด๋์ ์ํ ๊ฐ์ฒด
์ธ๋ถ์ ์๋ฒ ๊ฐ์ ์์ฒญ๊ณผ ์๋ต์ ๋ณด๋ผ ๋๋ ๊ฐ ๊ณ์ธต๊ฐ ์ด๋ ์ ์ฌ์ฉํ๋ค.
DTO๋ ์ ๋ฌํ๊ณ ์ ํ๋ ๋ฐ์ดํฐ๋ง์ ๋ด๊ณ ์์ด getter, setter๋ฅผ ๊ฐ์ง๋ฉฐ, ๋ก์ง์ ๊ฐ์ง์ง ์๋๋ค.
(ํ๋ฐฐ ๋ฐ์ค๋ผ๊ณ ์๊ฐํ๋ฉด ํธํ๋ค. ํ๋ฐฐ ๋ฐ์ค = DTO, ํ๋ฐฐ ๋ด์ฉ๋ฌผ = ๋ฐ์ดํฐ)
๊ตฌํ ๋ฐฉ์์ ๋ฐ๋ผ ๊ฐ๋ณ, ๋ถ๋ณ ๊ฐ์ฒด๋ก ํ์ฉํ ์ ์๋ค.
setter๋ก ๊ฐ์ ์์ ํ ์ ์๋๋ก ๊ตฌํํ๋ ๋ฐฉ์
public class exampleDto {
private String name;
public void setName(String newName) {
this.name = newName;
}
public String getName() {
return name;
}
}
์์ฑ์์ getter๋ฅผ ์ฌ์ฉํด ๊ฐ์ ์์ ํ ์ ์๋๋ก ๊ตฌํํ๋ ๋ฐฉ์
๋ฐ์ดํฐ์ ๋ถ๋ณ์ฑ์ ๋ณด์ฅํ๋ค.
public class exampleDto {
private String name;
public exampleDto(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
๋ฐ์ดํฐ ์ด๋์ ์ํ ๊ฐ์ฒด์ด๊ธฐ ๋๋ฌธ์ ๊ฐ๋ณ๋ณด๋ค๋ ๋ถ๋ณ์ผ๋ก ๊ตฌํํด ๋ฐ์ดํฐ๋ฅผ ๋ด๋ ์ฉ๋๋ก๋ง ๊ตฌํํ๋ ๊ฒ์ด ์ข๋ค.
๋, ์์ฒญ๊ณผ ์๋ต์์ ์ฌ์ฉํ๋ DTO๋ฅผ ๊ตฌ๋ถํด ๊ฐ๋ฐํ๋ ๊ฒ์ด ์ ์ง๋ณด์์ ์ข๋ค.
Spring boot ๊ธฐ๋ฐ REST API๋ฅผ ๊ตฌํํ๋ ๊ฒ์ ๊ธฐ์ค์ผ๋ก ์ค๋ช ํด๋ณด๊ฒ ๋ค.
@AllArgsConstructor
@NoArgsConstructor
@Getter
public class requestDto {
private String name;
}
์ธ๋ถ์์ name์ด๋ผ๋ ๋ฐ์ดํฐ๋ฅผ ์๋ฒ๋ก ์ ๋ฌํ๊ธฐ ์ํ DTO์ด๋ค.
@getter๋ฅผ ์ฌ์ฉํด getter ๋ฉ์๋๋ฅผ ๋ฐ๋ก ์์ฑํ์ง ์์์ผ๋ฉฐ, ์์ฑ์ ๋ํ ์ด๋
ธํ
์ด์
์ ์ฌ์ฉํ๋ค.
์ด๋ฅผ ์ด์ฉํด ์๋ฒ์์ DTO์ ๊ฐ์ ๊ฐ์ ธ์ ์ฌ์ฉํ ์ ์๋ค.
// front -> back
{
"name" : "์๋
"
}
์ธ๋ถ์์ body์ JSON ํ์์ ๋ฐ์ดํฐ๋ฅผ ์ ๋ฌํ ๋ ํด๋น DTO์์ ์ ์ํ ๋ฐ์ดํฐ ์ด๋ฆ(name)์ ๋ด์ ์ ๋ฌํ๋ค.
@Getter
public class responseDto {
private final String name;
public responseDto(String name) {
this.name = name;
}
}
์๋ฒ์์ Entity๋ฅผ DTO๋ก ๋งตํํ๊ธฐ ์ํ ์์ฑ์๊ฐ ์กด์ฌํ๊ณ , @Getter๋ฅผ ํตํด ๊ฐ์ ๊ฐ์ ธ์ฌ ์ ์๋ค.
Data Access Object
Database์ ์ ๊ทผํ๋ ์ญํ ์ ํ๋ ๊ฐ์ฒด
์ฆ ๋ฐ์ดํฐ์ CRUD ๊ธฐ๋ฅ์ ์ ๋ดํ๋ ๊ฐ์ฒด์ด๋ค.
// DAO Interface
public interface UserDAO {
User getUserById(int id);
List<User> getAllUsers();
void insertUser(User user);
void updateUser(User user);
void deleteUser(int id);
}
// DAO
public class UserDAOImpl implements UserDAO {
private Connection connection;
public UserDAOImpl(Connection connection) {
this.connection = connection;
}
@Override
public User getUserById(int id) throws SQLException {
String query = "SELECT * FROM users WHERE id = ?";
try (PreparedStatement psmt = connection.prepareStatement(query)) {
psmt.setInt(1, id);
try (ResultSet rs = psmt.executeQuery()) {
if (rs.next()) {
return new User(rs.getInt("id"), rs.getString("name"), rs.getString("email"));
}
}
}
return null;
}
// ๋ค๋ฅธ ๋ฉ์๋ (insert, update, delete) ๊ตฌํ ๊ฐ๋ฅ
}
PreparedStatement๋ฅผ ์ฌ์ฉํด ์ฟผ๋ฆฌ๋ฌธ(CRUD)์ ์คํํ๊ณ , ๊ฒฐ๊ณผ๋ฅผ ๋ฐ์์ ๊ฐ์ฒด๋ก ๋ฐํํ๋ค.
public class UserService {
private UserDAO userDAO;
public UserService(UserDAO userDAO) {
this.userDAO = userDAO;
}
public User getUserById(int id) {
return userDAO.getUserById(id);
}
}
์๋น์ค ๊ณ์ธต์์๋ DAO ๊ฐ์ฒด๋ฅผ ํตํด ๋ฐ์ดํฐ๋ฅผ ์ฒ๋ฆฌํ๋ค.
์ฐธ๊ณ -DTO, DAO
์ฐธ๊ณ -DTO, DAO ์ฌ์ฉ ์ด์
์ฐธ๊ณ -DAO ์์