From 1cd5e3ad847a655dab4e0e2054a124bb86a54b62 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=8B=A0=EC=A2=85=ED=99=94?= <77482065+jjongwa@users.noreply.github.com> Date: Wed, 11 Oct 2023 00:53:49 +0900 Subject: [PATCH] =?UTF-8?q?[JDBC=20=EB=9D=BC=EC=9D=B4=EB=B8=8C=EB=9F=AC?= =?UTF-8?q?=EB=A6=AC=20=EA=B5=AC=ED=98=84=ED=95=98=EA=B8=B0=20-=204?= =?UTF-8?q?=EB=8B=A8=EA=B3=84]=20=EB=94=94=EB=85=B8(=EC=8B=A0=EC=A2=85?= =?UTF-8?q?=ED=99=94)=20=EB=AF=B8=EC=85=98=20=EC=A0=9C=EC=B6=9C=ED=95=A9?= =?UTF-8?q?=EB=8B=88=EB=8B=A4.=20(#543)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * refactor: Transaction synchronization 적용 * refactor: Transaction Service 추상화 * refactor: 패키지 구조 변경 및 Executor 추상화 * refactor: null 처리 일관성있게 변경 * refactor: resource 미리 초기화 및 unbind시 remove 하도록 변경 * refactor: query와 queryForObject에서도 동일한 connection을 사용하도록 변경 * refactor: 네이밍 변경 --- .../main/java/com/techcourse/dao/UserDao.java | 6 -- .../com/techcourse/dao/UserHistoryDao.java | 5 +- .../com/techcourse/service/UserService.java | 55 ++----------------- .../service/impl/AppUserService.java | 36 ++++++++++++ .../service/impl/TxUserService.java | 35 ++++++++++++ .../service/MockUserHistoryDao.java | 3 +- .../techcourse/service/UserServiceTest.java | 20 ++++--- .../jdbc/core/AutoClosableTemplate.java | 22 ++------ .../jdbc/datasource/DataSourceUtils.java | 11 ++-- .../transaction/support/ServiceExecutor.java | 40 ++++++++++++++ .../TransactionSynchronizationManager.java | 27 +++++++-- .../support/TransactionTemplate.java | 6 ++ 12 files changed, 169 insertions(+), 97 deletions(-) create mode 100644 app/src/main/java/com/techcourse/service/impl/AppUserService.java create mode 100644 app/src/main/java/com/techcourse/service/impl/TxUserService.java create mode 100644 jdbc/src/main/java/org/springframework/transaction/support/ServiceExecutor.java create mode 100644 jdbc/src/main/java/org/springframework/transaction/support/TransactionTemplate.java diff --git a/app/src/main/java/com/techcourse/dao/UserDao.java b/app/src/main/java/com/techcourse/dao/UserDao.java index 73ead66878..2941d0b407 100644 --- a/app/src/main/java/com/techcourse/dao/UserDao.java +++ b/app/src/main/java/com/techcourse/dao/UserDao.java @@ -1,7 +1,6 @@ package com.techcourse.dao; import com.techcourse.domain.User; -import java.sql.Connection; import java.util.List; import javax.sql.DataSource; import org.slf4j.Logger; @@ -42,11 +41,6 @@ public void update(final User user) { jdbcTemplate.execute(sql, user.getAccount(), user.getPassword(), user.getEmail(), user.getId()); } - public void update(final Connection conn, final User user) { - final var sql = "update users set account = ?, password = ?, email = ? where id = ?"; - jdbcTemplate.execute(conn, sql, user.getAccount(), user.getPassword(), user.getEmail(), 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 483e5c650e..5332550f15 100644 --- a/app/src/main/java/com/techcourse/dao/UserHistoryDao.java +++ b/app/src/main/java/com/techcourse/dao/UserHistoryDao.java @@ -1,7 +1,6 @@ package com.techcourse.dao; import com.techcourse.domain.UserHistory; -import java.sql.Connection; import javax.sql.DataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -21,7 +20,7 @@ public UserHistoryDao(final JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } - public void log(final Connection conn, final UserHistory userHistory) { + public void log(final UserHistory userHistory) { final var sql = "insert into user_history (" + "user_id, " + "account, " @@ -33,7 +32,7 @@ public void log(final Connection conn, final UserHistory userHistory) { log.debug("query = {}", sql); - jdbcTemplate.execute(conn, sql, + jdbcTemplate.execute(sql, userHistory.getUserId(), userHistory.getAccount(), userHistory.getPassword(), diff --git a/app/src/main/java/com/techcourse/service/UserService.java b/app/src/main/java/com/techcourse/service/UserService.java index 0d997af2ea..b14dbcacbf 100644 --- a/app/src/main/java/com/techcourse/service/UserService.java +++ b/app/src/main/java/com/techcourse/service/UserService.java @@ -1,59 +1,12 @@ 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.Connection; -import java.sql.SQLException; -import javax.sql.DataSource; -import org.springframework.dao.DataAccessException; -import org.springframework.jdbc.datasource.DataSourceUtils; -public class UserService { +public interface UserService { - private final UserDao userDao; - private final UserHistoryDao userHistoryDao; + User findById(final long id); - public UserService(final UserDao userDao, final UserHistoryDao userHistoryDao) { - this.userDao = userDao; - this.userHistoryDao = userHistoryDao; - } + void insert(final User user); - 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) { - final DataSource dataSource = DataSourceConfig.getInstance(); - Connection conn = null; - try { - conn = dataSource.getConnection(); - conn.setAutoCommit(false); - - final User user = findById(id); - user.changePassword(newPassword); - - userDao.update(conn, user); - userHistoryDao.log(conn, new UserHistory(user, createBy)); - conn.commit(); - } catch (SQLException e) { - try { - conn.rollback(); - } catch (SQLException exception) { - throw new DataAccessException(exception); - } - } finally { - try { - conn.close(); - } catch (SQLException e) { - throw new DataAccessException(e); - } - } - } + void changePassword(final long id, final String newPassword, final String createBy); } diff --git a/app/src/main/java/com/techcourse/service/impl/AppUserService.java b/app/src/main/java/com/techcourse/service/impl/AppUserService.java new file mode 100644 index 0000000000..6572d3465d --- /dev/null +++ b/app/src/main/java/com/techcourse/service/impl/AppUserService.java @@ -0,0 +1,36 @@ +package com.techcourse.service.impl; + +import com.techcourse.dao.UserDao; +import com.techcourse.dao.UserHistoryDao; +import com.techcourse.domain.User; +import com.techcourse.domain.UserHistory; +import com.techcourse.service.UserService; + +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(long id) { + return userDao.findById(id); + } + + @Override + public void insert(User user) { + userDao.insert(user); + } + + @Override + public void changePassword(long id, String newPassword, 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/impl/TxUserService.java b/app/src/main/java/com/techcourse/service/impl/TxUserService.java new file mode 100644 index 0000000000..4e9c63205a --- /dev/null +++ b/app/src/main/java/com/techcourse/service/impl/TxUserService.java @@ -0,0 +1,35 @@ +package com.techcourse.service.impl; + +import com.techcourse.config.DataSourceConfig; +import com.techcourse.domain.User; +import com.techcourse.service.UserService; +import org.springframework.transaction.support.ServiceExecutor; + +public class TxUserService implements UserService { + + private final UserService userService; + private final ServiceExecutor serviceExecutor; + + public TxUserService(final UserService userService) { + this.userService = userService; + this.serviceExecutor = new ServiceExecutor(DataSourceConfig.getInstance()); + } + + @Override + public User findById(final long id) { + return userService.findById(id); + } + + @Override + public void insert(final User user) { + userService.insert(user); + } + + @Override + public void changePassword(final long id, final String newPassword, final String createBy) { + serviceExecutor.execute(() -> { + userService.changePassword(id, newPassword, createBy); + return null; + }); + } +} diff --git a/app/src/test/java/com/techcourse/service/MockUserHistoryDao.java b/app/src/test/java/com/techcourse/service/MockUserHistoryDao.java index 930200453d..2ee12b195f 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,7 +12,7 @@ public MockUserHistoryDao(final JdbcTemplate jdbcTemplate) { } @Override - public void log(final Connection conn, final UserHistory userHistory) { + 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/UserServiceTest.java index 2d4abce635..c58d811662 100644 --- a/app/src/test/java/com/techcourse/service/UserServiceTest.java +++ b/app/src/test/java/com/techcourse/service/UserServiceTest.java @@ -1,18 +1,19 @@ 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.service.impl.AppUserService; +import com.techcourse.service.impl.TxUserService; 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; class UserServiceTest { @@ -32,7 +33,7 @@ void setUp() { @Test void testChangePassword() { final var userHistoryDao = new UserHistoryDao(jdbcTemplate); - final var userService = new UserService(userDao, userHistoryDao); + final var userService = new AppUserService(userDao, userHistoryDao); final var newPassword = "qqqqq"; final var createBy = "gugu"; @@ -47,7 +48,10 @@ void testChangePassword() { void testTransactionRollback() { // 트랜잭션 롤백 테스트를 위해 mock으로 교체 final var userHistoryDao = new MockUserHistoryDao(jdbcTemplate); - final var userService = new UserService(userDao, userHistoryDao); + // 애플리케이션 서비스 + final var appUserService = new AppUserService(userDao, userHistoryDao); + // 트랜잭션 서비스 추상화 + final var userService = new TxUserService(appUserService); final var newPassword = "newPassword"; final var createBy = "gugu"; diff --git a/jdbc/src/main/java/org/springframework/jdbc/core/AutoClosableTemplate.java b/jdbc/src/main/java/org/springframework/jdbc/core/AutoClosableTemplate.java index 9c801c220f..3d422aeac6 100644 --- a/jdbc/src/main/java/org/springframework/jdbc/core/AutoClosableTemplate.java +++ b/jdbc/src/main/java/org/springframework/jdbc/core/AutoClosableTemplate.java @@ -10,6 +10,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.DataAccessException; +import org.springframework.jdbc.datasource.DataSourceUtils; abstract class AutoClosableTemplate { @@ -22,16 +23,7 @@ abstract class AutoClosableTemplate { } public void execute(final String sql, final Object... objects) { - try (final Connection conn = dataSource.getConnection(); - final PreparedStatement pstmt = preparedStatementAndSetValue(conn, sql, objects) - ) { - commandQuery(pstmt); - } catch (SQLException e) { - throw new DataAccessException(e); - } - } - - public void execute(final Connection conn, final String sql, final Object... objects) { + final Connection conn = DataSourceUtils.getConnection(dataSource); try (final PreparedStatement pstmt = preparedStatementAndSetValue(conn, sql, objects)) { commandQuery(pstmt); } catch (SQLException e) { @@ -40,9 +32,8 @@ public void execute(final Connection conn, final String sql, final Object... obj } public List query(final String sql, final RowMapper rowMapper, final Object... objects) { - try (final Connection conn = dataSource.getConnection(); - final PreparedStatement pstmt = preparedStatementAndSetValue(conn, sql, objects) - ) { + final Connection conn = DataSourceUtils.getConnection(dataSource); + try (final PreparedStatement pstmt = preparedStatementAndSetValue(conn, sql, objects)) { final ResultSet rs = pstmt.executeQuery(); return queryAll(rs, rowMapper); } catch (SQLException e) { @@ -52,9 +43,8 @@ public List query(final String sql, final RowMapper rowMapper, final O @Nullable public T queryForObject(final String sql, final RowMapper rowMapper, final Object... objects) { - try (final Connection conn = dataSource.getConnection(); - final PreparedStatement pstmt = preparedStatementAndSetValue(conn, sql, objects) - ) { + final Connection conn = DataSourceUtils.getConnection(dataSource); + try (final PreparedStatement pstmt = preparedStatementAndSetValue(conn, sql, objects)) { final ResultSet rs = pstmt.executeQuery(); return queryForOne(rs, rowMapper); } catch (SQLException e) { 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..9338161c3f 100644 --- a/jdbc/src/main/java/org/springframework/jdbc/datasource/DataSourceUtils.java +++ b/jdbc/src/main/java/org/springframework/jdbc/datasource/DataSourceUtils.java @@ -1,16 +1,15 @@ package org.springframework.jdbc.datasource; -import org.springframework.jdbc.CannotGetJdbcConnectionException; -import org.springframework.transaction.support.TransactionSynchronizationManager; - -import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; +import javax.sql.DataSource; +import org.springframework.jdbc.CannotGetJdbcConnectionException; +import org.springframework.transaction.support.TransactionSynchronizationManager; -// 4단계 미션에서 사용할 것 public abstract class DataSourceUtils { - private DataSourceUtils() {} + private DataSourceUtils() { + } public static Connection getConnection(DataSource dataSource) throws CannotGetJdbcConnectionException { Connection connection = TransactionSynchronizationManager.getResource(dataSource); diff --git a/jdbc/src/main/java/org/springframework/transaction/support/ServiceExecutor.java b/jdbc/src/main/java/org/springframework/transaction/support/ServiceExecutor.java new file mode 100644 index 0000000000..765dcd29ed --- /dev/null +++ b/jdbc/src/main/java/org/springframework/transaction/support/ServiceExecutor.java @@ -0,0 +1,40 @@ +package org.springframework.transaction.support; + +import java.sql.Connection; +import java.sql.SQLException; +import javax.sql.DataSource; +import org.springframework.dao.DataAccessException; +import org.springframework.jdbc.datasource.DataSourceUtils; + +public class ServiceExecutor { + + private final DataSource dataSource; + + public ServiceExecutor(DataSource dataSource) { + this.dataSource = dataSource; + } + + public T execute(TransactionTemplate executor) { + final Connection conn = DataSourceUtils.getConnection(dataSource); + try { + conn.setAutoCommit(false); + final T result = executor.execute(); + conn.commit(); + return result; + } catch (Exception e) { + rollback(conn); + throw new DataAccessException(e); + } finally { + DataSourceUtils.releaseConnection(conn, dataSource); + TransactionSynchronizationManager.unbindResource(dataSource); + } + } + + private void rollback(final Connection conn) { + try { + conn.rollback(); + } catch (SQLException exception) { + throw new DataAccessException(exception); + } + } +} 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..768c0689b0 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,40 @@ package org.springframework.transaction.support; -import javax.sql.DataSource; import java.sql.Connection; +import java.util.HashMap; import java.util.Map; +import javax.annotation.Nullable; +import javax.sql.DataSource; public abstract class TransactionSynchronizationManager { - private static final ThreadLocal> resources = new ThreadLocal<>(); + private static final ThreadLocal> resources = ThreadLocal.withInitial(HashMap::new); - private TransactionSynchronizationManager() {} + private TransactionSynchronizationManager() { + } + @Nullable public static Connection getResource(DataSource key) { - return null; + final Map dataSourceConnMap = resources.get(); + if (dataSourceConnMap == null) { + return null; + } + return dataSourceConnMap.get(key); } public static void bindResource(DataSource key, Connection value) { + Map dataSourceConnMap = resources.get(); + if (dataSourceConnMap == null) { + dataSourceConnMap = new HashMap<>(); + resources.set(dataSourceConnMap); + } + dataSourceConnMap.put(key, value); } public static Connection unbindResource(DataSource key) { - return null; + final Map dataSourceConnMap = resources.get(); + final Connection removedConn = dataSourceConnMap.remove(key); + resources.remove(); + return removedConn; } } diff --git a/jdbc/src/main/java/org/springframework/transaction/support/TransactionTemplate.java b/jdbc/src/main/java/org/springframework/transaction/support/TransactionTemplate.java new file mode 100644 index 0000000000..56490cba88 --- /dev/null +++ b/jdbc/src/main/java/org/springframework/transaction/support/TransactionTemplate.java @@ -0,0 +1,6 @@ +package org.springframework.transaction.support; + +@FunctionalInterface +public interface TransactionTemplate { + T execute(); +}