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 구현하기 - 2단계] 하디(전동혁) 미션 제출합니다. #353

Merged
merged 5 commits into from
Oct 3, 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
16 changes: 12 additions & 4 deletions app/src/main/java/com/techcourse/dao/UserDao.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package com.techcourse.dao;

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

Expand Down Expand Up @@ -41,14 +43,20 @@ public List<User> findAll() {

public User findById(final Long id) {
String sql = "select id, account, password, email from users where id = ?";
return jdbcTemplate.queryForObject(sql, rowMapper(), id)
.orElseThrow(() -> new IllegalArgumentException("User not found"));
try {
return jdbcTemplate.queryForObject(sql, rowMapper(), id);
} catch (DataAccessException e) {
throw new UserFoundException("유저가 없거나 2명 이상 입니다.", e);
}
}

public User findByAccount(final String account) {
String sql = "select id, account, password, email from users where account = ?";
return jdbcTemplate.queryForObject(sql, rowMapper(), account)
.orElseThrow(() -> new IllegalArgumentException("User not found"));
try {
return jdbcTemplate.queryForObject(sql, rowMapper(), account);
} catch (DataAccessException e) {
throw new UserFoundException("유저가 없거나 2명 이상 입니다.", e);
}
}

public RowMapper<User> rowMapper() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.techcourse.dao.exception;

public class UserFoundException extends RuntimeException {

public UserFoundException(String message, Throwable cause) {
super(message, cause);
}
}
6 changes: 4 additions & 2 deletions app/src/test/java/com/techcourse/dao/UserDaoTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,18 @@
import com.techcourse.config.DataSourceConfig;
import com.techcourse.domain.User;
import com.techcourse.support.jdbc.init.DatabasePopulatorUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;

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

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class UserDaoTest {

private UserDao userDao;

@BeforeEach
@BeforeAll
void setup() {
DatabasePopulatorUtils.execute(DataSourceConfig.getInstance());

Expand Down
130 changes: 46 additions & 84 deletions jdbc/src/main/java/org/springframework/jdbc/core/JdbcTemplate.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.exception.DatabaseResourceException;

import javax.sql.DataSource;
import java.sql.Connection;
Expand All @@ -10,7 +12,7 @@
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;

public class JdbcTemplate {

Expand All @@ -23,126 +25,86 @@ public JdbcTemplate(final DataSource dataSource) {
}

public void update(String sql, Object... args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = getConnection();
preparedStatement = getPreparedStatement(connection, sql, args);
preparedStatement.executeUpdate();
} catch (SQLException e) {
throw new IllegalArgumentException("Update Exception");
} finally {
closeResources(connection, preparedStatement, resultSet);
}
template(this::executeUpdate, sql, args);
}

public <T> List<T> query(String sql, RowMapper<T> rowMapper, Object... args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = getConnection();
preparedStatement = getPreparedStatement(connection, sql, args);
resultSet = getResultSet(preparedStatement);
Function<PreparedStatement, List<T>> query = preparedStatement -> {
ResultSet resultSet = executeQuery(preparedStatement);
return getObjects(resultSet, rowMapper);
} catch (Exception e) {
throw new IllegalArgumentException("Find Exception");
} finally {
closeResources(connection, preparedStatement, resultSet);
}
};
return template(query, sql, args);
}

public <T> Optional<T> queryForObject(String sql, RowMapper<T> rowMapper, Object... args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = getConnection();
preparedStatement = getPreparedStatement(connection, sql, args);
resultSet = getResultSet(preparedStatement);
return getObject(resultSet, rowMapper);
} catch (Exception e) {
throw new IllegalArgumentException("Find Exception");
} finally {
closeResources(connection, preparedStatement, resultSet);
public <T> T queryForObject(String sql, RowMapper<T> rowMapper, Object... args) {
List<T> results = query(sql, rowMapper, args);
if (results.isEmpty()) {
throw new DataAccessException("Data not found.");
}
}

private Connection getConnection() {
try {
return dataSource.getConnection();
} catch (SQLException e) {
throw new IllegalArgumentException("Connection cannot be acquired.");
if (results.size() >= 2) {
throw new DataAccessException("More than one data found");
}
return results.get(0);
}

private PreparedStatement getPreparedStatement(Connection connection, String sql, Object... args) {
private int executeUpdate(PreparedStatement preparedStatement) {
try {
PreparedStatement preparedStatement = connection.prepareStatement(sql);
for (int idx = 1; idx <= args.length; idx++) {
preparedStatement.setObject(idx, args[idx - 1]);
}
return preparedStatement;
return preparedStatement.executeUpdate();
} catch (SQLException e) {
throw new IllegalArgumentException("PreparedStatement cannot be acquired.");
throw new DatabaseResourceException(
"Database access error.", e);
}
}

private ResultSet getResultSet(PreparedStatement preparedStatement) {
private ResultSet executeQuery(PreparedStatement preparedStatement) {
try {
return preparedStatement.executeQuery();
} catch (SQLException e) {
throw new IllegalArgumentException("ResultSet cannot be acquired.");
throw new DatabaseResourceException(
"ResultSet cannot be acquired or PreparedStatement is already closed.", e);
}
}

private <T> List<T> getObjects(ResultSet resultSet, RowMapper<T> rowMapper) {
List<T> results = new ArrayList<>();
while (true) {
Optional<T> result = getObject(resultSet, rowMapper);
if (result.isPresent()) {
results.add(result.get());
continue;
try {
while (resultSet.next()) {
T result = rowMapper.map(resultSet);
results.add(result);
}
break;
} catch (SQLException e) {
throw new DatabaseResourceException("ResultSet is already closed", e);
}
return results;
}

private <T> Optional<T> getObject(ResultSet resultSet, RowMapper<T> rowMapper) {
try {
if (resultSet.next()) {
return Optional.of(rowMapper.map(resultSet));
}
return Optional.empty();
private <T> T template(Function<PreparedStatement, T> function, String sql, Object... args) {
try (
Connection connection = getConnection();
PreparedStatement preparedStatement = getPreparedStatement(connection, sql, args)) {
return function.apply(preparedStatement);
} catch (SQLException e) {
throw new IllegalArgumentException("Mapping fail");
throw new IllegalArgumentException();
}
}

private void closeResources(Connection connection,
PreparedStatement preparedStatement,
ResultSet resultSet) {
try {
if (resultSet != null) {
resultSet.close();
}
} catch (SQLException ignored) {
}

private Connection getConnection() {
try {
if (preparedStatement != null) {
preparedStatement.close();
}
} catch (SQLException ignored) {
return dataSource.getConnection();
} catch (SQLException e) {
throw new DatabaseResourceException("Connection cannot be acquired.", e);
}
}

private PreparedStatement getPreparedStatement(Connection connection, String sql, Object... args) {
try {
if (connection != null) {
connection.close();
PreparedStatement preparedStatement = connection.prepareStatement(sql);
for (int idx = 1; idx <= args.length; idx++) {
preparedStatement.setObject(idx, args[idx - 1]);
}
} catch (SQLException ignored) {
return preparedStatement;
} catch (SQLException e) {
throw new DatabaseResourceException("PreparedStatement cannot be acquired.", e);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package org.springframework.jdbc.exception;

import java.sql.SQLException;

public class DatabaseResourceException extends RuntimeException {

public DatabaseResourceException(String message, SQLException e) {
super(message, e);
}
}
Loading