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단계] 블랙캣(송우석) 미션 제출합니다🚀 #580

Merged
merged 7 commits into from
Oct 18, 2023
33 changes: 33 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,33 @@
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.support.TransactionTemplate;

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));
}
}
30 changes: 30 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,30 @@
package com.techcourse.service;

import com.techcourse.domain.User;
import org.springframework.jdbc.support.TransactionTemplate;

public class TxUserService implements UserService {

private final UserService userService;
private final TransactionTemplate transactionTemplate;

public TxUserService(final UserService userService, final TransactionTemplate transactionTemplate) {
this.userService = userService;
this.transactionTemplate = transactionTemplate;
}

@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) {
transactionTemplate.execute(() -> userService.changePassword(id, newPassword, createBy));
}
}
41 changes: 4 additions & 37 deletions app/src/main/java/com/techcourse/service/UserService.java
Original file line number Diff line number Diff line change
@@ -1,46 +1,13 @@
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.support.TransactionTemplate;

public class UserService {
public interface UserService {

private final UserDao userDao;
private final UserHistoryDao userHistoryDao;
private final TransactionTemplate transactionTemplate;
User findById(final long id);

public UserService(final UserDao userDao, final UserHistoryDao userHistoryDao, final TransactionTemplate transactionTemplate) {
this.userDao = userDao;
this.userHistoryDao = userHistoryDao;
this.transactionTemplate = transactionTemplate;
}
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 var user = findById(id);
user.changePassword(newPassword);

transactionTemplate.execute(() -> {
updateUser(user);
writeUserHistory(new UserHistory(user, createBy));
});
}

private void updateUser(final User user) {
userDao.update(user);
}

private void writeUserHistory(final UserHistory userHistory) {
userHistoryDao.log(userHistory);
}
void changePassword(final long id, final String newPassword, final String createBy);
}
11 changes: 11 additions & 0 deletions app/src/test/java/com/techcourse/dao/UserDaoTest.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
package com.techcourse.dao;

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

import com.techcourse.config.DataSourceConfig;
import com.techcourse.domain.User;
import com.techcourse.support.jdbc.init.DatabasePopulatorUtils;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.jdbc.core.JdbcTemplate;

class UserDaoTest {

Expand Down Expand Up @@ -66,4 +70,11 @@ void update() {

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

@AfterAll
static void truncate() {
final JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceConfig.getInstance());
final String truncate = "TRUNCATE TABLE users RESTART IDENTITY";
jdbcTemplate.update(truncate);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,27 +8,28 @@
import com.techcourse.dao.UserHistoryDao;
import com.techcourse.domain.User;
import com.techcourse.support.jdbc.init.DatabasePopulatorUtils;
import org.junit.jupiter.api.AfterAll;
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 org.springframework.jdbc.support.TransactionTemplate;

@Disabled
class UserServiceTest {
class TxUserServiceTest {

private JdbcTemplate jdbcTemplate;
private UserDao userDao;
private UserHistoryDao userHistoryDao;
private TransactionTemplate transactionTemplate;
private UserService appUserService;

@BeforeEach
void setUp() {
this.jdbcTemplate = new JdbcTemplate(DataSourceConfig.getInstance());
this.userDao = new UserDao(jdbcTemplate);
this.userHistoryDao = new UserHistoryDao(jdbcTemplate);
this.transactionTemplate = new TransactionTemplate(DataSourceConfig.getInstance());
this.appUserService = new AppUserService(userDao, userHistoryDao);

DatabasePopulatorUtils.execute(DataSourceConfig.getInstance());
final var user = new User("gugu", "password", "[email protected]");
Expand All @@ -37,7 +38,7 @@ void setUp() {

@Test
void testChangePassword() {
final var userService = new UserService(userDao, userHistoryDao, transactionTemplate);
final var userService = new TxUserService(appUserService, transactionTemplate);

final var newPassword = "qqqqq";
final var createBy = "gugu";
Expand All @@ -52,7 +53,8 @@ void testChangePassword() {
void testTransactionRollback() {
// 트랜잭션 롤백 테스트를 위해 mock으로 교체
final var userHistoryDao = new MockUserHistoryDao(jdbcTemplate);
final var userService = new UserService(userDao, userHistoryDao, transactionTemplate);
final var mockAppUserService = new AppUserService(userDao, userHistoryDao);
final var userService = new TxUserService(mockAppUserService, transactionTemplate);

final var newPassword = "newPassword";
final var createBy = "gugu";
Expand All @@ -64,4 +66,11 @@ void testTransactionRollback() {

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

@AfterAll
static void truncate() {
final JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceConfig.getInstance());
final String truncate = "TRUNCATE TABLE users RESTART IDENTITY";
jdbcTemplate.update(truncate);
}
}
26 changes: 22 additions & 4 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,7 @@

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
Expand All @@ -10,12 +11,13 @@
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.exception.IncorrectResultSizeDataAccessException;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.support.ConnectionHolder;
import org.springframework.jdbc.support.TransactionManager;

public class JdbcTemplate {

private static final Logger log = LoggerFactory.getLogger(JdbcTemplate.class);
private static final int QUERY_PARAMETER_STEP = 1;

private final DataSource dataSource;

Expand Down Expand Up @@ -49,13 +51,29 @@ public <T> Optional<T> queryForObject(final String sql, final RowMapper<T> rowMa
}

private <T> T execute(final String sql, final PreparedStatementCallback<T> callback, final Object... parameters) {
try (final ConnectionHolder connectionHolder = TransactionManager.getConnectionHolder(dataSource);
final PreparedStatement preparedStatement = connectionHolder.createPrepareStatement(sql, parameters);
try (final ConnectionHolder connectionHolder = DataSourceUtils.getConnectionHolder(dataSource);
final PreparedStatement preparedStatement = createPrepareStatement(connectionHolder, sql, parameters);
) {
return callback.callback(preparedStatement);
} catch (final Exception e) {
} catch (final SQLException e) {
log.error(e.getMessage(), e);
throw new DataAccessException(e);
} catch (final Exception e) {
log.error(e.getMessage(), e);
throw new RuntimeException(e);
}
}

public PreparedStatement createPrepareStatement(
Copy link

Choose a reason for hiding this comment

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

지난번에 고민하셨던 부분이었던 것 같은데 jdbcTemplate으로 옮겨주셨네요!

Copy link
Author

Choose a reason for hiding this comment

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

저번에 밀리의 리뷰를 들어보고 고민해보니 아무래도 jdbcTemplate 가 더 맞는거 같아서 복구 시켜놓았습니다!

final ConnectionHolder connectionHolder,
final String sql, final Object[] parameters
) throws SQLException {
final PreparedStatement preparedStatement = connectionHolder.getConnection().prepareStatement(sql);

for (int index = 0; index < parameters.length; index++) {
preparedStatement.setObject(index + QUERY_PARAMETER_STEP, parameters[index]);
}

return preparedStatement;
}
}
Original file line number Diff line number Diff line change
@@ -1,37 +1,22 @@
package org.springframework.jdbc.datasource;

import java.sql.Connection;
import javax.sql.DataSource;
import org.springframework.jdbc.CannotGetJdbcConnectionException;
import org.springframework.jdbc.support.ConnectionHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

// 4단계 미션에서 사용할 것
public abstract class DataSourceUtils {

private DataSourceUtils() {}

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

try {
connection = dataSource.getConnection();
TransactionSynchronizationManager.bindResource(dataSource, connection);
return connection;
} catch (SQLException ex) {
throw new CannotGetJdbcConnectionException("Failed to obtain JDBC Connection", ex);
}
private DataSourceUtils() {
}

public static void releaseConnection(Connection connection, DataSource dataSource) {
try {
connection.close();
} catch (SQLException ex) {
throw new CannotGetJdbcConnectionException("Failed to close JDBC Connection");
public static ConnectionHolder getConnectionHolder(DataSource dataSource) throws CannotGetJdbcConnectionException {
final Connection connection = TransactionSynchronizationManager.getResource(dataSource);
if (TransactionSynchronizationManager.isTransactionBegan()) {
return ConnectionHolder.activeTransaction(connection);
}

return ConnectionHolder.disableTransaction(connection);
}
}
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
package org.springframework.jdbc.support;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class ConnectionHolder implements AutoCloseable {

private static final int QUERY_PARAMETER_STEP = 1;

private final Connection connection;
private final boolean isTransactionActive;

Expand All @@ -16,16 +12,6 @@ private ConnectionHolder(final Connection connection, final boolean isTransactio
this.isTransactionActive = isTransactionActive;
Copy link

Choose a reason for hiding this comment

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

그리고 지난번에 DM으로 말씀해주셨던 부분인데 궁금한 점이 생겨 질문 드려요!

DataSourceUtils 구현 부 때문에 자바에서 제공하는 try-with-resources 를 활용하지 못한다는 느낌이 들었어요!

저는 블랙캣이 해당 부분을 해소하기 위해 ConnectionHolder에서 AutoCloseable을 구현하셨다고 생각했습니다.
해당 부분을 적용해주신 뒤에 질문 주셨던 내용이었는지 기억이 안 나네요..
저는 ConnectionHolder에서 AutoCloseable을 구현하면서 close()를 재정의해주면서 try-with-resources에 사용할 수 있게 되었다고 생각했는데 제가 이해한 게 맞을까요??

}

public PreparedStatement createPrepareStatement(final String sql, final Object[] parameters) throws SQLException {
final PreparedStatement preparedStatement = connection.prepareStatement(sql);

for (int index = 0; index < parameters.length; index++) {
preparedStatement.setObject(index + QUERY_PARAMETER_STEP, parameters[index]);
}

return preparedStatement;
}

public static ConnectionHolder activeTransaction(final Connection connection) {
return new ConnectionHolder(connection, true);
}
Expand All @@ -34,6 +20,10 @@ public static ConnectionHolder disableTransaction(final Connection connection) {
return new ConnectionHolder(connection, false);
}

public Connection getConnection() {
return connection;
}

@Override
public void close() throws Exception {
if (!isTransactionActive) {
Copy link

Choose a reason for hiding this comment

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

여기에서 connection을 close하기 전 autoCommit을 true로 변경해주어야 합니다!
커넥션 풀에 저장된 커넥션을 돌려서 사용하기 때문에 autoCommit이 false인 상태로 close를 하면 나중에 다른 스레드에 할당될 커넥션의 autoCommit이 false인 상태로 커넥션을 할당 받기 때문이라고 합니다!

Expand Down
Loading
Loading