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

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

Merged
merged 4 commits into from
Sep 27, 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
111 changes: 19 additions & 92 deletions app/src/main/java/com/techcourse/dao/UserDao.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,120 +2,47 @@

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

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class UserDao {

private static final Logger log = LoggerFactory.getLogger(UserDao.class);
private static final RowMapper<User> USER_ROW_MAPPER = resultSet -> new User(
resultSet.getLong("id"),
resultSet.getString("account"),
resultSet.getString("password"),
resultSet.getString("email")
);

private final DataSource dataSource;

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

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) {}
}
String sql = "insert into users (account, password, email) values (?, ?, ?)";
jdbcTemplate.update(sql, user.getAccount(), user.getPassword(), user.getEmail());
}

public void update(final User user) {
// todo
String sql = "UPDATE users SET account = ?, password = ? WHERE email = ?";
jdbcTemplate.update(sql, user.getAccount(), user.getPassword(), user.getEmail());
}

public List<User> findAll() {
// todo
return null;
String sql = "SELECT id, account, password, email FROM users";
return jdbcTemplate.query(sql, USER_ROW_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) {}
}
String sql = "select id, account, password, email from users where id = ?";
return jdbcTemplate.queryForObject(sql, USER_ROW_MAPPER, id);
}

public User findByAccount(final String account) {
// todo
return null;
String sql = "select id, account, password, email from users where account = ?";
return jdbcTemplate.queryForObject(sql, USER_ROW_MAPPER, account);
}
}
3 changes: 2 additions & 1 deletion app/src/test/java/com/techcourse/dao/UserDaoTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import com.techcourse.support.jdbc.init.DatabasePopulatorUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.jdbc.core.JdbcTemplate;

import static org.assertj.core.api.Assertions.assertThat;

Expand All @@ -16,7 +17,7 @@ class UserDaoTest {
void setup() {
DatabasePopulatorUtils.execute(DataSourceConfig.getInstance());

userDao = new UserDao(DataSourceConfig.getInstance());
userDao = new UserDao(new JdbcTemplate(DataSourceConfig.getInstance()));
final var user = new User("gugu", "password", "[email protected]");
userDao.insert(user);
}
Expand Down
60 changes: 60 additions & 0 deletions jdbc/src/main/java/org/springframework/jdbc/core/JdbcTemplate.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,15 @@

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;

import javax.sql.DataSource;
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 JdbcTemplate {

Expand All @@ -14,4 +21,57 @@ public class JdbcTemplate {
public JdbcTemplate(final DataSource dataSource) {
this.dataSource = dataSource;
}

public <T> List<T> query(final String sql, final RowMapper<T> rowMapper, final Object... args) {
try (final Connection connection = dataSource.getConnection();
final PreparedStatement preparedStatement = getPreparedStatement(connection, sql, args);
final ResultSet resultSet = preparedStatement.executeQuery()) {

List<T> results = new ArrayList<>();
while (resultSet.next()) {
results.add(rowMapper.mapToRow(resultSet));
}

return results;
} catch (final SQLException e) {
log.error(e.getMessage(), e);
throw new DataAccessException(e.getMessage(), e);
}
}

public <T> T queryForObject(final String sql, final RowMapper<T> rowMapper, final Object... args) {
try (final Connection connection = dataSource.getConnection();
final PreparedStatement preparedStatement = getPreparedStatement(connection, sql, args);
final ResultSet resultSet = preparedStatement.executeQuery()) {

if (!resultSet.next()) {
return null;
}

return rowMapper.mapToRow(resultSet);
} catch (final SQLException e) {
log.error(e.getMessage(), e);
throw new DataAccessException(e.getMessage(), e);
}
}

public void update(final String sql, final Object... args) {
try (final Connection connection = dataSource.getConnection();
final PreparedStatement preparedStatement = getPreparedStatement(connection, sql, args)) {
preparedStatement.executeUpdate();
} catch (final SQLException e) {
log.error(e.getMessage(), e);
throw new DataAccessException(e.getMessage(), e);
}
}

private PreparedStatement getPreparedStatement(final Connection connection, final String sql, final Object[] args) throws SQLException {
PreparedStatement preparedStatement = connection.prepareStatement(sql);

for (int i = 0; i < args.length; i++) {
preparedStatement.setObject(i + 1, args[i]);
}

return preparedStatement;
}
}
10 changes: 10 additions & 0 deletions jdbc/src/main/java/org/springframework/jdbc/core/RowMapper.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package org.springframework.jdbc.core;

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

@FunctionalInterface
public interface RowMapper<T> {

T mapToRow(final ResultSet resultSet) throws SQLException;
}
Loading