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단계] 우르(김현우) 미션 제출합니다. #550

Merged
merged 6 commits into from
Oct 10, 2023
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));
}
}
41 changes: 41 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,41 @@
package com.techcourse.service;

import com.techcourse.domain.User;
import javax.sql.DataSource;
import org.springframework.transaction.support.TransactionSynchronizationManager;

public class TxUserService implements UserService {

private final UserService userService;
private final DataSource dataSource;

public TxUserService(final UserService userService, final DataSource dataSource) {
this.userService = userService;
this.dataSource = dataSource;
}

@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) {
TransactionSynchronizationManager.start();

try {
userService.changePassword(id, newPassword, createBy);
TransactionSynchronizationManager.commit(dataSource);
} catch (Exception e) {
TransactionSynchronizationManager.rollback(dataSource);
throw e;
} finally {
TransactionSynchronizationManager.release(dataSource);
}
}
Comment on lines +27 to +40

Choose a reason for hiding this comment

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

라이브러리를 사용하는 입장에서는 일일이 커넥션을 관리할 필요 없이 TransactionSynchronizationManager를 통해 편하게 트랜잭션 관리를 할 수 있게 되었네요! 👍

}
40 changes: 4 additions & 36 deletions app/src/main/java/com/techcourse/service/UserService.java
Original file line number Diff line number Diff line change
@@ -1,43 +1,11 @@
package com.techcourse.service;

import com.techcourse.dao.UserDao;
import com.techcourse.dao.UserHistoryDao;
import com.techcourse.domain.User;
import com.techcourse.domain.UserHistory;
import org.springframework.jdbc.core.TransactionManager;

public class UserService {
public interface UserService {

private final UserDao userDao;
private final UserHistoryDao userHistoryDao;
User findById(final long id);
void insert(final User user);
void changePassword(final long id, final String newPassword, final String createBy);

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) {
final var user = findById(id);

TransactionManager.start();
try {
user.changePassword(newPassword);
userDao.update(user);
userHistoryDao.log(new UserHistory(user, createBy));
TransactionManager.commit();
} catch (Exception e) {
TransactionManager.rollback();
throw e;
} finally {
TransactionManager.release();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import com.techcourse.dao.UserHistoryDao;
import com.techcourse.domain.User;
import com.techcourse.support.jdbc.init.DatabasePopulatorUtils;
import javax.sql.DataSource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.junit.jupiter.api.BeforeEach;
Expand All @@ -13,25 +14,27 @@
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;

class UserServiceTest {
class AppUserServiceTest {

private JdbcTemplate jdbcTemplate;
private UserDao userDao;
private DataSource dataSource;

@BeforeEach
void setUp() {
this.jdbcTemplate = new JdbcTemplate(DataSourceConfig.getInstance());
dataSource = DataSourceConfig.getInstance();
this.jdbcTemplate = new JdbcTemplate(dataSource);
this.userDao = new UserDao(jdbcTemplate);

DatabasePopulatorUtils.execute(DataSourceConfig.getInstance());
DatabasePopulatorUtils.execute(dataSource);
final var user = new User("gugu", "password", "hkkang@woowahan.com");
userDao.insert(user);
}

@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";
Expand All @@ -46,7 +49,8 @@ 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 TxUserService userService = new TxUserService(appUserService, dataSource);

final var newPassword = "newPassword";
final var createBy = "gugu";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,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 Down Expand Up @@ -42,7 +44,7 @@ public <T> Optional<T> query(final String sql, RowMapper<T> rowMapper, final Obj
return Optional.ofNullable(result.get(0));
} catch (SQLException e) {
log.error(e.getMessage(), e);
throw new RuntimeException(e);
throw new DataAccessException(e);
}
}

Expand Down Expand Up @@ -71,7 +73,7 @@ public <T> List<T> queryPlural(
return extractResultFrom(resultSet, rowMapper);
} catch (SQLException e) {
log.error(e.getMessage(), e);
throw new RuntimeException(e);
throw new DataAccessException(e);
}
}

Expand All @@ -88,7 +90,7 @@ private <T> List<T> extractResultFrom(final ResultSet resultSet, final RowMapper

public void execute(final String sql, final Object... values) {

final Connection connection = TransactionManager.getConnection(dataSource);
final Connection connection = DataSourceUtils.getConnection(dataSource);

try (
final PreparedStatement pstmt = connection.prepareStatement(sql)
Expand All @@ -101,7 +103,7 @@ public void execute(final String sql, final Object... values) {
pstmt.executeUpdate();
} catch (SQLException e) {
log.error(e.getMessage(), e);
throw new RuntimeException(e);
throw new DataAccessException(e);
}
}
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.springframework.jdbc.datasource;

import java.util.function.Function;
import org.springframework.jdbc.CannotGetJdbcConnectionException;
import org.springframework.transaction.support.TransactionSynchronizationManager;

Expand All @@ -10,28 +11,29 @@
// 4단계 미션에서 사용할 것
public abstract class DataSourceUtils {

private DataSourceUtils() {}
private DataSourceUtils() {
}

public static Connection getConnection(DataSource dataSource) throws CannotGetJdbcConnectionException {
Connection connection = TransactionSynchronizationManager.getResource(dataSource);
if (connection != null) {
return connection;
}
public static Connection getConnection(DataSource dataSource) {
return TransactionSynchronizationManager.getResource(dataSource)
.orElseGet(() -> createConnection(dataSource));
}

try {
connection = dataSource.getConnection();
TransactionSynchronizationManager.bindResource(dataSource, connection);
return connection;
} catch (SQLException ex) {
throw new CannotGetJdbcConnectionException("Failed to obtain JDBC Connection", ex);
}
private static Connection createConnection(final DataSource dataSource) {
try {
final Connection connection = dataSource.getConnection();
TransactionSynchronizationManager.bindResource(dataSource, connection);
return connection;
} catch (SQLException ex) {
throw new CannotGetJdbcConnectionException("Failed to obtain JDBC Connection", ex);
}
}
Comment on lines +22 to +30

Choose a reason for hiding this comment

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

세심하게 메서드 분리 잘 해주셨네요 😄


public static void releaseConnection(Connection connection, DataSource dataSource) {
try {
connection.close();
} catch (SQLException ex) {
throw new CannotGetJdbcConnectionException("Failed to close JDBC Connection");
}
public static void releaseConnection(Connection connection) {
try {
connection.close();
} catch (SQLException ex) {
throw new CannotGetJdbcConnectionException("Failed to close JDBC Connection");
}
}
}
Loading
Loading