diff --git a/app/src/main/java/com/techcourse/dao/UserDao.java b/app/src/main/java/com/techcourse/dao/UserDao.java index 568c1abf00..575b425af7 100644 --- a/app/src/main/java/com/techcourse/dao/UserDao.java +++ b/app/src/main/java/com/techcourse/dao/UserDao.java @@ -31,11 +31,6 @@ public void update(final User user) { jdbcTemplate.update(sql, user.getPassword(), user.getEmail(), user.getAccount(), user.getId()); } - public void update(final Connection connection, final User user) { - final var sql = "update users set password = ?, email = ?, account = ? where id = ?"; - jdbcTemplate.update(sql, user.getPassword(), user.getEmail(), user.getAccount(), user.getId()); - } - public List findAll() { final var sql = "select id, account, password, email from users"; return jdbcTemplate.query(sql, USER_ROW_MAPPER); diff --git a/app/src/main/java/com/techcourse/dao/UserHistoryDao.java b/app/src/main/java/com/techcourse/dao/UserHistoryDao.java index 9554b1adf9..38600a75c1 100644 --- a/app/src/main/java/com/techcourse/dao/UserHistoryDao.java +++ b/app/src/main/java/com/techcourse/dao/UserHistoryDao.java @@ -12,12 +12,6 @@ public UserHistoryDao(final JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } - public void log(final Connection connection, final UserHistory userHistory) { - final var sql = "insert into user_history (user_id, account, password, email, created_at, created_by) values (?, ?, ?, ?, ?, ?)"; - jdbcTemplate.update(connection, sql, userHistory.getUserId(), userHistory.getAccount(), userHistory.getPassword(), - userHistory.getEmail(), userHistory.getCreatedAt(), userHistory.getCreateBy()); - } - public void log(final UserHistory userHistory) { final var sql = "insert into user_history (user_id, account, password, email, created_at, created_by) values (?, ?, ?, ?, ?, ?)"; jdbcTemplate.update(sql, userHistory.getUserId(), userHistory.getAccount(), userHistory.getPassword(), diff --git a/app/src/main/java/com/techcourse/service/AppUserService.java b/app/src/main/java/com/techcourse/service/AppUserService.java new file mode 100644 index 0000000000..3bac27f084 --- /dev/null +++ b/app/src/main/java/com/techcourse/service/AppUserService.java @@ -0,0 +1,36 @@ +package com.techcourse.service; + +import com.techcourse.dao.UserDao; +import com.techcourse.dao.UserHistoryDao; +import com.techcourse.domain.User; +import com.techcourse.domain.UserHistory; + +public class AppUserService implements UserService { + + private final UserDao userDao; + private final UserHistoryDao userHistoryDao; + + public AppUserService(final UserDao userDao, final UserHistoryDao userHistoryDao) { + this.userDao = userDao; + this.userHistoryDao = userHistoryDao; + } + + @Override + public User findById(final long id) { + return userDao.findById(id); + } + + @Override + public void insert(final User user) { + userDao.insert(user); + } + + @Override + public void changePassword(final long id, final String newPassword, final String createBy) { + final var user = findById(id); + user.changePassword(newPassword); + userDao.update(user); + userHistoryDao.log(new UserHistory(user, createBy)); + } + +} diff --git a/app/src/main/java/com/techcourse/service/TxUserService.java b/app/src/main/java/com/techcourse/service/TxUserService.java new file mode 100644 index 0000000000..ea99cfb725 --- /dev/null +++ b/app/src/main/java/com/techcourse/service/TxUserService.java @@ -0,0 +1,83 @@ +package com.techcourse.service; + +import com.techcourse.config.DataSourceConfig; +import com.techcourse.domain.User; +import java.sql.SQLException; +import org.springframework.dao.DataAccessException; +import org.springframework.jdbc.datasource.DataSourceUtils; + +public class TxUserService implements UserService { + + private final UserService userService; + + public TxUserService(final UserService userService) { + this.userService = userService; + } + + @Override + public User findById(final long id) { + User user; + + final var dataSource = DataSourceConfig.getInstance(); + final var connection = DataSourceUtils.getConnection(dataSource); + try { + connection.setAutoCommit(false); + user = userService.findById(id); + + connection.commit(); + } catch (final Exception e) { + try { + connection.rollback(); + } catch (SQLException ex) { + throw new DataAccessException(ex); + } + throw new DataAccessException(e); + } finally { + DataSourceUtils.releaseConnection(connection, dataSource); + } + + return user; + } + + @Override + public void insert(final User user) { + final var dataSource = DataSourceConfig.getInstance(); + final var connection = DataSourceUtils.getConnection(dataSource); + try { + connection.setAutoCommit(false); + userService.insert(user); + + connection.commit(); + } catch (final Exception e) { + try { + connection.rollback(); + } catch (SQLException ex) { + throw new DataAccessException(ex); + } + throw new DataAccessException(e); + } finally { + DataSourceUtils.releaseConnection(connection, dataSource); + } + } + + @Override + public void changePassword(final long id, final String newPassword, final String createBy) { + final var dataSource = DataSourceConfig.getInstance(); + final var connection = DataSourceUtils.getConnection(dataSource); + try { + connection.setAutoCommit(false); + userService.changePassword(id, newPassword, createBy); + + connection.commit(); + } catch (final Exception e) { + try { + connection.rollback(); + } catch (SQLException ex) { + throw new DataAccessException(ex); + } + throw new DataAccessException(e); + } finally { + DataSourceUtils.releaseConnection(connection, dataSource); + } + } +} diff --git a/app/src/main/java/com/techcourse/service/UserService.java b/app/src/main/java/com/techcourse/service/UserService.java index d8782ba089..42d01bf760 100644 --- a/app/src/main/java/com/techcourse/service/UserService.java +++ b/app/src/main/java/com/techcourse/service/UserService.java @@ -1,47 +1,10 @@ package com.techcourse.service; -import com.techcourse.config.DataSourceConfig; -import com.techcourse.dao.UserDao; -import com.techcourse.dao.UserHistoryDao; import com.techcourse.domain.User; -import com.techcourse.domain.UserHistory; -import java.sql.SQLException; -import org.springframework.dao.DataAccessException; -public class UserService { - - private final UserDao userDao; - private final UserHistoryDao userHistoryDao; - - public UserService(final UserDao userDao, final UserHistoryDao userHistoryDao) { - this.userDao = userDao; - this.userHistoryDao = userHistoryDao; - } - - public User findById(final long id) { - return userDao.findById(id); - } - - public void insert(final User user) { - userDao.insert(user); - } - - public void changePassword(final long id, final String newPassword, final String createBy) throws SQLException { - final var connection = DataSourceConfig.getInstance().getConnection(); - try { - connection.setAutoCommit(false); - final var user = findById(id); - user.changePassword(newPassword); - userDao.update(connection, user); - userHistoryDao.log(connection, new UserHistory(user, createBy)); - - connection.commit(); - } catch (final Exception e) { - connection.rollback(); - throw new DataAccessException(e); - } finally { - connection.close(); - } - } +public interface UserService { + User findById(final long id); + void insert(final User user); + void changePassword(final long id, final String newPassword, final String createBy); } diff --git a/app/src/test/java/com/techcourse/service/AppUserServiceTest.java b/app/src/test/java/com/techcourse/service/AppUserServiceTest.java new file mode 100644 index 0000000000..29c1f89a33 --- /dev/null +++ b/app/src/test/java/com/techcourse/service/AppUserServiceTest.java @@ -0,0 +1,43 @@ +package com.techcourse.service; + +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 java.sql.SQLException; +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; + +class AppUserServiceTest { + + private JdbcTemplate jdbcTemplate; + private UserDao userDao; + + @BeforeEach + void setUp() { + this.jdbcTemplate = new JdbcTemplate(DataSourceConfig.getInstance()); + this.userDao = new UserDao(jdbcTemplate); + + DatabasePopulatorUtils.execute(DataSourceConfig.getInstance()); + final var user = new User("gugu", "password", "hkkang@woowahan.com"); + userDao.insert(user); + } + + @Test + void testChangePassword() throws SQLException { + final var userHistoryDao = new UserHistoryDao(jdbcTemplate); + final var userService = new AppUserService(userDao, userHistoryDao); + + final var newPassword = "qqqqq"; + final var createBy = "gugu"; + userService.changePassword(1L, newPassword, createBy); + + final var actual = userService.findById(1L); + + assertThat(actual.getPassword()).isEqualTo(newPassword); + } +} diff --git a/app/src/test/java/com/techcourse/service/MockUserHistoryDao.java b/app/src/test/java/com/techcourse/service/MockUserHistoryDao.java index 789dced668..c720ab0d58 100644 --- a/app/src/test/java/com/techcourse/service/MockUserHistoryDao.java +++ b/app/src/test/java/com/techcourse/service/MockUserHistoryDao.java @@ -2,7 +2,6 @@ import com.techcourse.dao.UserHistoryDao; import com.techcourse.domain.UserHistory; -import java.sql.Connection; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; @@ -13,8 +12,8 @@ public MockUserHistoryDao(final JdbcTemplate jdbcTemplate) { } @Override - public void log(final Connection connection, final UserHistory userHistory) { - System.out.println("로그뜰까요아닐까용오오오"); + public void log(final UserHistory userHistory) { throw new DataAccessException(); } + } diff --git a/app/src/test/java/com/techcourse/service/UserServiceTest.java b/app/src/test/java/com/techcourse/service/TxUserServiceTest.java similarity index 54% rename from app/src/test/java/com/techcourse/service/UserServiceTest.java rename to app/src/test/java/com/techcourse/service/TxUserServiceTest.java index 957478d82d..df13c9c0d5 100644 --- a/app/src/test/java/com/techcourse/service/UserServiceTest.java +++ b/app/src/test/java/com/techcourse/service/TxUserServiceTest.java @@ -2,23 +2,17 @@ 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.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; -import java.sql.SQLException; - import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertThrows; -@Disabled -class UserServiceTest { +class TxUserServiceTest { private JdbcTemplate jdbcTemplate; private UserDao userDao; @@ -32,37 +26,24 @@ void setUp() { final var user = new User("gugu", "password", "hkkang@woowahan.com"); userDao.insert(user); } - - @Test - void testChangePassword() throws SQLException { - final var userHistoryDao = new UserHistoryDao(jdbcTemplate); - final var userService = new UserService(userDao, userHistoryDao); - - final var newPassword = "qqqqq"; - final var createBy = "gugu"; - userService.changePassword(1L, newPassword, createBy); - - final var actual = userService.findById(1L); - - assertThat(actual.getPassword()).isEqualTo(newPassword); - } - @Test void testTransactionRollback() { // 트랜잭션 롤백 테스트를 위해 mock으로 교체 - // 트랜잭션이 정상 동작하는지 확인하기 위해 의도적으로 MockUserHistoryDao에서 예외를 발생시킨다. - final MockUserHistoryDao mockUserHistoryDao = new MockUserHistoryDao(jdbcTemplate); - final var userService = new UserService(userDao, mockUserHistoryDao); + final var userHistoryDao = new MockUserHistoryDao(jdbcTemplate); + // 애플리케이션 서비스 + final var appUserService = new AppUserService(userDao, userHistoryDao); + // 트랜잭션 서비스 추상화 + final var userService = new TxUserService(appUserService); final var newPassword = "newPassword"; final var createBy = "gugu"; + // 트랜잭션이 정상 동작하는지 확인하기 위해 의도적으로 MockUserHistoryDao에서 예외를 발생시킨다. + assertThrows(DataAccessException.class, + () -> userService.changePassword(1L, newPassword, createBy)); final var actual = userService.findById(1L); - assertAll( - () -> assertThrows(DataAccessException.class, - () -> userService.changePassword(1L, newPassword, createBy)), - () -> assertThat(actual.getPassword()).isNotEqualTo(newPassword) - ); + assertThat(actual.getPassword()).isNotEqualTo(newPassword); } + } diff --git a/jdbc/src/main/java/org/springframework/jdbc/core/JdbcTemplate.java b/jdbc/src/main/java/org/springframework/jdbc/core/JdbcTemplate.java index 0a5cc69419..50e4510bc0 100644 --- a/jdbc/src/main/java/org/springframework/jdbc/core/JdbcTemplate.java +++ b/jdbc/src/main/java/org/springframework/jdbc/core/JdbcTemplate.java @@ -12,6 +12,7 @@ import javax.sql.DataSource; import org.springframework.dao.DataAccessException; import org.springframework.dao.SizeException; +import org.springframework.jdbc.datasource.DataSourceUtils; public class JdbcTemplate { @@ -29,7 +30,7 @@ public T queryForObject(final String sql, final RowMapper rowMapper, fina throw new SizeException("too many result. expected 1 but was " + results.size()); } if (results.isEmpty()) { - throw new SizeException("no result"); + throw new DataAccessException("no result"); } return results.get(0); } @@ -40,14 +41,14 @@ public T queryForObject(final Connection connection, final String sql, final throw new SizeException("too many result. expected 1 but was " + results.size()); } if (results.isEmpty()) { - throw new SizeException("no result"); + throw new DataAccessException("no result"); } return results.get(0); } public List query(final String sql, final RowMapper rowMapper, final Object... parameters) { - try (final Connection conn = dataSource.getConnection(); - final PreparedStatement preparedStatement = conn.prepareStatement(sql); + final var conn = getConnection(); + try (final PreparedStatement preparedStatement = conn.prepareStatement(sql); final ResultSet resultSet = executeQuery(preparedStatement, parameters)) { log.debug("query : {}", sql); return mapResults(rowMapper, resultSet); @@ -90,8 +91,8 @@ private List mapResults(final RowMapper rowMapper, final ResultSet res } public void update(final String sql, final Object... parameters) { - try (final Connection conn = dataSource.getConnection(); - final PreparedStatement preparedStatement = conn.prepareStatement(sql)) { + final Connection conn = getConnection(); + try (final PreparedStatement preparedStatement = conn.prepareStatement(sql)) { log.debug("query : {}", sql); setParameters(preparedStatement, parameters); @@ -114,4 +115,8 @@ public void update(final Connection conn, final String sql, final Object... para } } + private Connection getConnection() { + return DataSourceUtils.getConnection(dataSource); + } + } diff --git a/jdbc/src/main/java/org/springframework/jdbc/datasource/DataSourceUtils.java b/jdbc/src/main/java/org/springframework/jdbc/datasource/DataSourceUtils.java index 3c40bfec52..be2f114ac1 100644 --- a/jdbc/src/main/java/org/springframework/jdbc/datasource/DataSourceUtils.java +++ b/jdbc/src/main/java/org/springframework/jdbc/datasource/DataSourceUtils.java @@ -29,6 +29,7 @@ public static Connection getConnection(DataSource dataSource) throws CannotGetJd public static void releaseConnection(Connection connection, DataSource dataSource) { try { + TransactionSynchronizationManager.unbindResource(dataSource); connection.close(); } catch (SQLException ex) { throw new CannotGetJdbcConnectionException("Failed to close JDBC Connection"); diff --git a/jdbc/src/main/java/org/springframework/transaction/support/TransactionSynchronizationManager.java b/jdbc/src/main/java/org/springframework/transaction/support/TransactionSynchronizationManager.java index 715557fc66..4f1199b94b 100644 --- a/jdbc/src/main/java/org/springframework/transaction/support/TransactionSynchronizationManager.java +++ b/jdbc/src/main/java/org/springframework/transaction/support/TransactionSynchronizationManager.java @@ -1,23 +1,41 @@ package org.springframework.transaction.support; -import javax.sql.DataSource; import java.sql.Connection; +import java.util.HashMap; import java.util.Map; +import javax.sql.DataSource; public abstract class TransactionSynchronizationManager { private static final ThreadLocal> resources = new ThreadLocal<>(); - private TransactionSynchronizationManager() {} + private TransactionSynchronizationManager() { + } public static Connection getResource(DataSource key) { - return null; + final Map dataSourceConnectionMap = resources.get(); + + if (dataSourceConnectionMap == null) { + return null; + } + return dataSourceConnectionMap.get(key); } public static void bindResource(DataSource key, Connection value) { + if (resources.get() == null) { + resources.set(new HashMap<>()); + } + + resources.get().put(key, value); } public static Connection unbindResource(DataSource key) { - return null; + final Map dataSourceConnectionMap = resources.get(); + + if (dataSourceConnectionMap == null) { + return null; + } + return dataSourceConnectionMap.remove(key); } + } diff --git a/jdbc/src/test/java/nextstep/jdbc/JdbcTemplateTest.java b/jdbc/src/test/java/nextstep/jdbc/JdbcTemplateTest.java index 3e7fa0c702..3a0a830125 100644 --- a/jdbc/src/test/java/nextstep/jdbc/JdbcTemplateTest.java +++ b/jdbc/src/test/java/nextstep/jdbc/JdbcTemplateTest.java @@ -49,7 +49,7 @@ void throwExceptionWhenResultSetIsEmpty() throws SQLException { //expect assertThatThrownBy( () -> jdbcTemplate.queryForObject(sql, (rs, rowNum) -> new Integer(1), params)) - .isInstanceOf(SizeException.class); + .isInstanceOf(DataAccessException.class); } @Test