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 라이브러리 구현하기 - 4단계] 말랑(신동훈) 미션 제출합니다. #558

Merged
merged 10 commits into from
Oct 12, 2023
5 changes: 0 additions & 5 deletions app/src/main/java/com/techcourse/dao/UserDao.java
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,6 @@ public void update(final User user) {
jdbcTemplate.execute(sql, user.getAccount(), user.getPassword(), user.getEmail(), user.getId());
}

public void update(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<User> findAll() {
final var sql = "select id, account, password, email from users";
return jdbcTemplate.queryForList(sql, userRowMapper);
Expand Down
5 changes: 2 additions & 3 deletions app/src/main/java/com/techcourse/dao/UserHistoryDao.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.techcourse.dao;

import com.techcourse.domain.UserHistory;
import java.sql.Connection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
Expand All @@ -16,9 +15,9 @@ public UserHistoryDao(final JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}

public void log(Connection conn, final UserHistory userHistory) {
public void log(final UserHistory userHistory) {
final var sql = "insert into user_history (user_id, account, password, email, created_at, created_by) values (?, ?, ?, ?, ?, ?)";
jdbcTemplate.execute(conn, sql,
jdbcTemplate.execute(sql,
userHistory.getUserId(),
userHistory.getAccount(),
userHistory.getPassword(),
Expand Down
32 changes: 32 additions & 0 deletions app/src/main/java/com/techcourse/service/AppUserService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
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;
}

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 var user = findById(id);
user.changePassword(newPassword);
userDao.update(user);
userHistoryDao.log(new UserHistory(user, createBy));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.techcourse.service;

import com.techcourse.domain.User;
import org.springframework.transaction.support.TxTemplate;

public class TxTemplateUserService implements UserService {

private final UserService delegate;
private final TxTemplate txTemplate;

public TxTemplateUserService(UserService delegate, TxTemplate txTemplate) {
this.delegate = delegate;
this.txTemplate = txTemplate;
}

public User findById(final long id) {
return delegate.findById(id);
}

public void insert(final User user) {
delegate.insert(user);
}

public void changePassword(final long id, final String newPassword, final String createBy) {
txTemplate.execute(() -> {
delegate.changePassword(id, newPassword, createBy);
});
}
}
44 changes: 44 additions & 0 deletions app/src/main/java/com/techcourse/service/TxUserService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package com.techcourse.service;

import com.techcourse.config.DataSourceConfig;
import com.techcourse.domain.User;
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 TxUserService implements UserService {

private final UserService delegate;
Copy link
Member

Choose a reason for hiding this comment

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

오홍 네이밍을 delegate로 하셨는데
어떨 때 이런 네이밍을 사용하는지 알려주실 수 있나요.? 처음 봐서요..!
구체적인 작업은 UserService가 하도록 위임한다는 뜻인가요?

Copy link
Author

Choose a reason for hiding this comment

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

음 사실 TxUserService에서 실제 로직은 다른 서비스에 위임하기 때문에, 이를 표현하기 위해서 이렇게 네이밍 했습니다!


public TxUserService(UserService delegate) {
this.delegate = delegate;
}

public User findById(final long id) {
return delegate.findById(id);
}

public void insert(final User user) {
delegate.insert(user);
}

public void changePassword(final long id, final String newPassword, final String createBy) {
DataSource dataSource = DataSourceConfig.getInstance();
try (Connection conn = DataSourceUtils.getConnection(dataSource)) {
try {
conn.setAutoCommit(false);
delegate.changePassword(id, newPassword, createBy);
conn.commit();
} catch (SQLException e) {
conn.rollback();
throw new DataAccessException(e);
} finally {
DataSourceUtils.releaseConnection(conn, dataSource);
}
} catch (SQLException e) {
throw new DataAccessException(e);
}
}
shin-mallang marked this conversation as resolved.
Show resolved Hide resolved
}
45 changes: 4 additions & 41 deletions app/src/main/java/com/techcourse/service/UserService.java
Original file line number Diff line number Diff line change
@@ -1,49 +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;

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) {
DataSource dataSource = DataSourceConfig.getInstance();
try (Connection conn = dataSource.getConnection()) {
try {
conn.setAutoCommit(false);
final var user = findById(id);
user.changePassword(newPassword);
userDao.update(conn, user);
userHistoryDao.log(conn, new UserHistory(user, createBy));
conn.commit();
} catch (Exception e) {
conn.rollback();
throw new DataAccessException(e);
}
} catch (SQLException e) {
throw new DataAccessException(e);
}
}
void changePassword(final long id, final String newPassword, final String createBy);
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -13,7 +12,7 @@ public MockUserHistoryDao(final JdbcTemplate jdbcTemplate) {
}

@Override
public void log(Connection conn, final UserHistory userHistory) {
public void log(final UserHistory userHistory) {
throw new DataAccessException();
}
}
29 changes: 27 additions & 2 deletions app/src/test/java/com/techcourse/service/UserServiceTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@
import com.techcourse.dao.UserHistoryDao;
import com.techcourse.domain.User;
import com.techcourse.support.jdbc.init.DatabasePopulatorUtils;
import javax.sql.DataSource;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.support.TxTemplate;

class UserServiceTest {

Expand All @@ -31,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 TxUserService(new AppUserService(userDao, userHistoryDao));

final var newPassword = "qqqqq";
final var createBy = "gugu";
Expand All @@ -46,7 +48,30 @@ 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";
// 트랜잭션이 정상 동작하는지 확인하기 위해 의도적으로 MockUserHistoryDao에서 예외를 발생시킨다.
assertThrows(DataAccessException.class,
() -> userService.changePassword(1L, newPassword, createBy));

final var actual = userService.findById(1L);

assertThat(actual.getPassword()).isNotEqualTo(newPassword);
}

@Test
void testTransactionWithTemplateRollback() {
// 트랜잭션 롤백 테스트를 위해 mock으로 교체
final var userHistoryDao = new MockUserHistoryDao(jdbcTemplate);
// 애플리케이션 서비스
final var appUserService = new AppUserService(userDao, userHistoryDao);
// 트랜잭션 서비스 추상화
final var userService = new TxTemplateUserService(appUserService, new TxTemplate(DataSourceConfig.getInstance()));

final var newPassword = "newPassword";
final var createBy = "gugu";
Expand Down
24 changes: 12 additions & 12 deletions jdbc/src/main/java/org/springframework/jdbc/core/JdbcTemplate.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.datasource.DataSourceUtils;

public class JdbcTemplate {

Expand All @@ -24,12 +26,9 @@ public void execute(String sql, Object... params) {
execute(sql, PreparedStatement::executeUpdate, params);
}

public void execute(Connection conn, String sql, Object... params) {
execute(conn, sql, PreparedStatement::executeUpdate, params);
}

public <T> T queryForObject(String sql, RowMapper<T> rowMapper, Object... params) {
return execute(sql, pstmt -> {
Connection connection = DataSourceUtils.getConnection(dataSource);
return execute(connection, sql, pstmt -> {
ResultSet resultSet = pstmt.executeQuery();
if (resultSet.next()) {
return rowMapper.mapRow(resultSet);
Expand All @@ -39,7 +38,8 @@ public <T> T queryForObject(String sql, RowMapper<T> rowMapper, Object... params
}

public <T> List<T> queryForList(String sql, RowMapper<T> rowMapper, Object... params) {
return execute(sql, pstmt -> {
Connection connection = DataSourceUtils.getConnection(dataSource);
return execute(connection, sql, pstmt -> {
ResultSet resultSet = pstmt.executeQuery();
List<T> result = new ArrayList<>();
while (resultSet.next()) {
Expand All @@ -50,21 +50,21 @@ public <T> List<T> queryForList(String sql, RowMapper<T> rowMapper, Object... pa
}

private <T> T execute(String sql, PreparedStatementFunction<T> function, Object... params) {
try (Connection connection = dataSource.getConnection();
PreparedStatement pstmt = preparedStatementWithParams(connection, sql, params)) {
Connection connection = DataSourceUtils.getConnection(dataSource);
try (PreparedStatement pstmt = preparedStatementWithParams(connection, sql, params)) {
shin-mallang marked this conversation as resolved.
Show resolved Hide resolved
return function.execute(pstmt);
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new RuntimeException(e);
throw new DataAccessException(e);
}
}

private <T> T execute(Connection conn, String sql, PreparedStatementFunction<T> function, Object... params) {
try (PreparedStatement pstmt = preparedStatementWithParams(conn, sql, params)) {
return function.execute(pstmt);
} catch (Exception e) {
} catch (SQLException e) {
log.error(e.getMessage(), e);
throw new RuntimeException(e);
throw new DataAccessException(e);
}
}
shin-mallang marked this conversation as resolved.
Show resolved Hide resolved

Expand All @@ -79,6 +79,6 @@ private PreparedStatement preparedStatementWithParams(Connection con, String sql
}

private interface PreparedStatementFunction<T> {
T execute(PreparedStatement pstmt) throws Exception;
T execute(PreparedStatement pstmt) throws SQLException;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ public static Connection getConnection(DataSource dataSource) throws CannotGetJd
if (connection != null) {
return connection;
}

try {
connection = dataSource.getConnection();
TransactionSynchronizationManager.bindResource(dataSource, connection);
Expand All @@ -30,6 +29,7 @@ public static Connection getConnection(DataSource dataSource) throws CannotGetJd
public static void releaseConnection(Connection connection, DataSource dataSource) {
try {
connection.close();
TransactionSynchronizationManager.unbindResource(dataSource);
} catch (SQLException ex) {
throw new CannotGetJdbcConnectionException("Failed to close JDBC Connection");
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,23 +1,39 @@
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<Map<DataSource, Connection>> resources = new ThreadLocal<>();

private TransactionSynchronizationManager() {}
private TransactionSynchronizationManager() {
}

@Nullable
public static Connection getResource(DataSource key) {
return null;
Map<DataSource, Connection> dataSourceConnectionMap = resources.get();
if (dataSourceConnectionMap == null) {
return null;
}
return dataSourceConnectionMap.get(key);
}

public static void bindResource(DataSource key, Connection value) {
resources.set(new HashMap<>() {{
put(key, value);
}});
}

public static Connection unbindResource(DataSource key) {
return null;
Map<DataSource, Connection> dataSourceConnectionMap = resources.get();
Connection remove = dataSourceConnectionMap.remove(key);
if (dataSourceConnectionMap.isEmpty()) {
resources.remove();
}
return remove;
}
}
Loading
Loading