Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[JDBC 라이브러리 구현하기 - 1단계] 우가(윤정욱) 미션 제출합니다. #285

Merged
merged 3 commits into from
Sep 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 25 additions & 87 deletions app/src/main/java/com/techcourse/dao/UserDao.java
Original file line number Diff line number Diff line change
@@ -1,121 +1,59 @@
package com.techcourse.dao;

import com.techcourse.domain.User;
import org.springframework.jdbc.core.JdbcTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

public class UserDao {

private static final Logger log = LoggerFactory.getLogger(UserDao.class);
private final RowMapper<User> mapper = resultSet -> {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이전 미션에서 크루분들이 주로 RowMapper는 static final 로 사용했던 것으로 알고있는데요!
우가는 final만 사용해주셨네요! 혹시 static을 붙이지 않은 이유가 있을까요?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

UserDao 가 생성될 때 생성되면 좋겠어서, final 만 선언했습니다.

final long id = resultSet.getLong("id");
final String account = resultSet.getString("account");
final String password = resultSet.getString("password");
final String email = resultSet.getString("email");

private final DataSource dataSource;
return new User(id, account, password, email);
};

private final JdbcTemplate jdbcTemplate;

public UserDao(final DataSource dataSource) {
this.dataSource = dataSource;
this(new JdbcTemplate(dataSource));
}

public UserDao(final JdbcTemplate jdbcTemplate) {
this.dataSource = null;
this.jdbcTemplate = jdbcTemplate;
}

public void insert(final User user) {
final var sql = "insert into users (account, password, email) values (?, ?, ?)";

Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = dataSource.getConnection();
pstmt = conn.prepareStatement(sql);

log.debug("query : {}", sql);

pstmt.setString(1, user.getAccount());
pstmt.setString(2, user.getPassword());
pstmt.setString(3, user.getEmail());
pstmt.executeUpdate();
} catch (SQLException e) {
log.error(e.getMessage(), e);
throw new RuntimeException(e);
} finally {
try {
if (pstmt != null) {
pstmt.close();
}
} catch (SQLException ignored) {}

try {
if (conn != null) {
conn.close();
}
} catch (SQLException ignored) {}
}
jdbcTemplate.execute(sql, user.getAccount(), user.getPassword(), user.getEmail());
}

public void update(final User user) {
// todo
final var sql = "update users set password = ? where id = ?";
Copy link

@eunbii0213 eunbii0213 Sep 28, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

지금은 password만 변경해주고 있는 것 같은데요!
final String sql = "update users set (account, password, email) = (?, ?, ?) where id = ?";
이런식으로 다른 정보도 update 할 수 있지 않을까요?
password만 Update를 작성한 이유가 궁금합니다!

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

오 감사합니다. 기존 User 로직이 비밀번호를 변경하는 거라 무의식적으로 password 만 변경했네용 😶


jdbcTemplate.execute(sql, user.getPassword(), user.getId());
}

public List<User> findAll() {
// todo
return null;
final var sql = "select id, account, password, email from users";

return jdbcTemplate.queryForObjects(sql, mapper);
}

public User findById(final Long id) {
final var sql = "select id, account, password, email from users where id = ?";

Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = dataSource.getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setLong(1, id);
rs = pstmt.executeQuery();

log.debug("query : {}", sql);

if (rs.next()) {
return new User(
rs.getLong(1),
rs.getString(2),
rs.getString(3),
rs.getString(4));
}
return null;
} catch (SQLException e) {
log.error(e.getMessage(), e);
throw new RuntimeException(e);
} finally {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException ignored) {}

try {
if (pstmt != null) {
pstmt.close();
}
} catch (SQLException ignored) {}

try {
if (conn != null) {
conn.close();
}
} catch (SQLException ignored) {}
}
return jdbcTemplate.queryForObject(sql, mapper, id);
}

public User findByAccount(final String account) {
// todo
return null;
final var sql = "select id, account, password, email from users where account = ?";

return jdbcTemplate.queryForObject(sql, mapper, account);
}
}
10 changes: 5 additions & 5 deletions app/src/test/java/com/techcourse/service/UserServiceTest.java
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
package com.techcourse.service;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;

import com.techcourse.config.DataSourceConfig;
import com.techcourse.dao.UserDao;
import com.techcourse.dao.UserHistoryDao;
import com.techcourse.domain.User;
import com.techcourse.support.jdbc.init.DatabasePopulatorUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;

@Disabled
class UserServiceTest {
Expand Down
68 changes: 66 additions & 2 deletions jdbc/src/main/java/org/springframework/jdbc/core/JdbcTemplate.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
package org.springframework.jdbc.core;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;

public class JdbcTemplate {

private static final Logger log = LoggerFactory.getLogger(JdbcTemplate.class);
Expand All @@ -14,4 +19,63 @@ public class JdbcTemplate {
public JdbcTemplate(final DataSource dataSource) {
this.dataSource = dataSource;
}

public void execute(final String sql, final Object... params) {
try (Connection conn = dataSource.getConnection();
PreparedStatement pstmt = makePreparedWhenHasParams(conn, sql, params)) {

log.debug("query : {}", sql);

pstmt.executeUpdate();
} catch (SQLException e) {
log.error(e.getMessage(), e);
throw new RuntimeException(e);
}
}

public <T> T queryForObject(final String sql, final RowMapper<T> mapper, Object... params) {
wugawuga marked this conversation as resolved.
Show resolved Hide resolved
try (Connection conn = dataSource.getConnection();
PreparedStatement pstmt = makePreparedWhenHasParams(conn, sql, params);
ResultSet rs = pstmt.executeQuery()) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ResultSet을 close()해주지 않은 이유가 있나요? 🤓

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

try-with-resources 로 해당 로직이 끝나면 자동적으로 close 를 호출해줍니다!


log.debug("query : {}", sql);

while (rs.next()) {
return mapper.get(rs);
}
return null;
} catch (SQLException e) {
log.error(e.getMessage(), e);
throw new RuntimeException(e);
wugawuga marked this conversation as resolved.
Show resolved Hide resolved
}
wugawuga marked this conversation as resolved.
Show resolved Hide resolved
}

private PreparedStatement makePreparedWhenHasParams(final Connection conn, final String sql, final Object[] params)
throws SQLException {
final PreparedStatement pstmt = conn.prepareStatement(sql);

for (int i = 0; i < params.length; i++) {
pstmt.setObject(i + 1, params[i]);
}
wugawuga marked this conversation as resolved.
Show resolved Hide resolved

return pstmt;
}

public <T> List<T> queryForObjects(final String sql, final RowMapper<T> mapper) {
try (Connection conn = dataSource.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery()) {

log.debug("query : {}", sql);

final var list = new ArrayList<T>();
wugawuga marked this conversation as resolved.
Show resolved Hide resolved
while (rs.next()) {
list.add(mapper.get(rs));
}
return list;
} catch (SQLException e) {
log.error(e.getMessage(), e);
throw new RuntimeException(e);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package org.springframework.jdbc.core;

import java.sql.ResultSet;
import java.sql.SQLException;

public interface RowMapper<T> {

T get(final ResultSet resultSet) throws SQLException;
}
1 change: 1 addition & 0 deletions study/src/main/java/aop/config/DataSourceConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ public class DataSourceConfig {
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.setName("test;DB_CLOSE_DELAY=-1;MODE=MYSQL;")
.addScript("classpath:schema.sql")
.build();
}
Expand Down
1 change: 1 addition & 0 deletions study/src/main/resources/application.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
spring:
jpa:
open-in-view: false
show-sql: true
generate-ddl: true
hibernate:
Expand Down
Loading