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단계] 메리(최승원) 미션 제출합니다 #584

Merged
merged 54 commits into from
Oct 15, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
54 commits
Select commit Hold shift + click to select a range
dc70d1d
패키지 위치 변경 및 코드 정리
kang-hyungu Sep 21, 2023
7182a49
패키지 위치 변경 및 코드 정리
kang-hyungu Sep 21, 2023
06379e5
패키지 위치 변경 및 코드 정리
kang-hyungu Sep 21, 2023
ae100c4
feat: jdbc를 이용한 모든 유저 정보 수정 기능 추가
swonny Oct 3, 2023
42708f0
feat: jdbc를 이용한 모든 유저 정보 조회 기능 추가
swonny Oct 3, 2023
2463faf
feat: jdbc를 이용한 유저 account로 정보 조회하는 기능 추가
swonny Oct 3, 2023
e48fbcd
feat: 단일 조회 객체 RowMapper 생성
swonny Oct 3, 2023
aa39a33
refactor: 아이디를 통한 유저 조회 중복 제거
swonny Oct 3, 2023
95aaf0c
feat: 계정을 통한 유저 조회 기능 구현
swonny Oct 3, 2023
8ff2b3a
feat: 복수 조회를 위한 메서드 생성 및 findAll 중복 제거
swonny Oct 3, 2023
4f04737
feat: update 중복 제거
swonny Oct 4, 2023
f2e785e
feat: insert 중복 제거
swonny Oct 4, 2023
edf550d
refactor: 단일 조회 try-with-resources 사용하도록 수정
swonny Oct 4, 2023
6d9a536
refactor: 단일 조회 아닌 경우에 대한 예외 처리 추가
swonny Oct 4, 2023
1a99a87
fix: 단일 조회 누락된 로직 추가
swonny Oct 4, 2023
8f7b50b
refactor: 복수 조회 메서드 try-with-resources 사용하도록 변경
swonny Oct 4, 2023
efdff4e
refactor: 수정 메서드 try-with-resources 사용하도록 변경
swonny Oct 4, 2023
1d0d0bb
refactor: 불필요한 제네릭 삭제
swonny Oct 4, 2023
a4bc31d
refactor: 데이터가 존재하지 않는 경우 예외 발생이 아닌 Optional을 반환하도록 변경
swonny Oct 4, 2023
3c8ffa6
refactor: 불필요한 필드 제거
swonny Oct 4, 2023
128b208
refactor: 조회하려는 사용자가 없는 경우 DAO에서 예외 발생하도록 변경
swonny Oct 4, 2023
66f2857
feat: 로그 출력
swonny Oct 4, 2023
c68ca2d
refactor: 단일 조회 시 파라미터를 가변인자로 받도록 변경
swonny Oct 4, 2023
f6fc7f6
refactor: 중복되는 로직 메서드로 추출
swonny Oct 4, 2023
14a555d
refactor: 복수 조회 메서드 네이밍 변경
swonny Oct 5, 2023
e1dbf23
refactor: 중복되는 자원 열고 닫는 로직 콜백 패턴 사용하여 제거
swonny Oct 5, 2023
97fa8af
refactor: 콜백에 사용되는 람다 함수 재정의
swonny Oct 5, 2023
99a2021
refactor: jdbc 연결 실패 시 커스텀 unchecked 예외 던지도록 수정
swonny Oct 5, 2023
3963ba3
Merge remote-tracking branch 'upstream/swonny' into step1
swonny Oct 8, 2023
d1c4068
test: 실습
swonny Oct 8, 2023
7a18ba7
refactor: userHistoryDao에서 jdbcTemplate 사용하도록 수정
swonny Oct 8, 2023
35e449d
refactor: 서비스 레이어에서 connection 생성해 같은 트랜잭션에서 재사용하도록 수정
swonny Oct 8, 2023
49309d7
test: 변경된 코드에 맞춰 테스트 코드 수정
swonny Oct 8, 2023
89fcfbe
refactor: 중복되는 자원 열고 닫는 로직 제거
swonny Oct 8, 2023
0c1873a
refactor: 메서드 네이밍 수정
swonny Oct 8, 2023
30ed91e
feat: 트랜잭션 종료 로직 추가
swonny Oct 8, 2023
c570870
refactor: 커스텀 예외를 던지도록 변경
swonny Oct 8, 2023
33dff91
refactor: preparedStatement try-catch 내부에서 생성하도록 변경
swonny Oct 8, 2023
3fc681d
fix: 첫 번째 파라미터만 추가되는 로직 수정
swonny Oct 8, 2023
b4316ef
test: UserHistoryDao 메서드 시그니처 변경에 따라 mock 메서드 시그니처 변경
swonny Oct 8, 2023
8b5b02d
test: UserDao 메서드 시그니처 변경에 따라 테스트 메서드 시그니처 변경
swonny Oct 8, 2023
fe1a0ce
refactor: 함수형 인터페이스 대소문자 변경
swonny Oct 8, 2023
6b0f3f5
Merge remote-tracking branch 'upstream/swonny' into step2
swonny Oct 9, 2023
c732706
refactor: 커넥션을 가져오는 부분을 DataSourceUtils에서 대신하도록 수정
swonny Oct 9, 2023
398d8c8
test: 요구사항에 맞춰 테스트 수정
swonny Oct 9, 2023
5d63d58
test: 커넥션 생성하는 로직 TransactionSynchronizationManager로 이동
swonny Oct 9, 2023
c588c40
refactor: 트랜잭션 관리 로직 TransactionSynchronizationManager로 이동
swonny Oct 9, 2023
70941b9
refactor: 트랜잭션 서비스 추상화
swonny Oct 9, 2023
95dcdfd
refactor: 불필요한 함수형 인터페이스 제거
swonny Oct 9, 2023
973c714
fix: 트랜잭션 종료되지 않은 경우 commit하지 않도록 변경
swonny Oct 9, 2023
e63cb29
fix: 트랜잭셔 매니저의 트랜잭션 시작과 종료가 정상적으로 동작하도록 수정
swonny Oct 14, 2023
05a153f
refactor: 트랜잭션 매니저 생성 및 TxUserService에서 트랜잭션 중복 로직 제거
swonny Oct 14, 2023
f21c08e
refactor: 트랜잭션 매니에서 커밋, 롤백 수행하도록 수정
swonny Oct 14, 2023
88ffa92
refactor: 예외 처리 로직을 TransactionManager에서 수행하도록 변경
swonny Oct 14, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions app/src/main/java/com/techcourse/dao/UserDao.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.SQLException;
import java.util.List;

public class UserDao {
Expand All @@ -25,29 +26,29 @@ public UserDao(final JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}

public int insert(final User user) {
public int insert(final User user) throws SQLException {
final var sql = "insert into users (account, password, email) values (?, ?, ?)";
log.debug("query : {}", sql);

return updateQuery(sql, user.getAccount(), user.getPassword(), user.getEmail());
}

private int updateQuery(final String sql, final Object... objects) {
private int updateQuery(final String sql, final Object... objects) throws SQLException {
final int updatedRows = jdbcTemplate.update(sql, objects);
if (updatedRows < 1) {
throw new RuntimeException("저장된 데이터가 없습니다.");
}
return updatedRows;
}

public int update(final User user) {
public int update(final User user) throws SQLException {
final var sql = "update users set (account, password, email) = (?, ?, ?)";
log.debug("query : {}", sql);

return updateQuery(sql, user.getAccount(), user.getPassword(), user.getEmail());
}

public List<User> findAll() {
public List<User> findAll() throws SQLException {
final var sql = "select id, account, password, email from users";
final List<User> users = jdbcTemplate.query(sql, userRowMapper);

Expand All @@ -56,7 +57,7 @@ public List<User> findAll() {
return users;
}

public User findById(final Long id) {
public User findById(final Long id) throws SQLException {
final var sql = "select id, account, password, email from users where id = ?";
final User user = jdbcTemplate.queryForObject(sql, userRowMapper, id)
.orElseThrow(() -> new RuntimeException("찾는 사용자가 존재하지 않습니다."));
Expand All @@ -66,7 +67,7 @@ public User findById(final Long id) {
return user;
}

public User findByAccount(final String account) {
public User findByAccount(final String account) throws SQLException {
final var sql = "select id, account, password, email from users where account = ?";
final User user = jdbcTemplate.queryForObject(sql, userRowMapper, account)
.orElseThrow(() -> new RuntimeException("찾는 사용자가 존재하지 않습니다."));
Expand Down
4 changes: 3 additions & 1 deletion app/src/main/java/com/techcourse/dao/UserHistoryDao.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;

import java.sql.SQLException;

public class UserHistoryDao {

private static final Logger log = LoggerFactory.getLogger(UserHistoryDao.class);
Expand All @@ -15,7 +17,7 @@ public UserHistoryDao(final JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}

public void log(final UserHistory userHistory) {
public void log(final UserHistory userHistory) throws SQLException {
final var sql = "insert into user_history (user_id, account, password, email, created_at, created_by) values (?, ?, ?, ?, ?, ?)";
jdbcTemplate.update(
sql,
Expand Down
10 changes: 6 additions & 4 deletions app/src/main/java/com/techcourse/service/AppUserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import com.techcourse.domain.User;
import com.techcourse.domain.UserHistory;

import java.sql.SQLException;

public class AppUserService implements UserService {

private final UserDao userDao;
Expand All @@ -16,20 +18,20 @@ public AppUserService(final UserDao userDao, final UserHistoryDao userHistoryDao
}

@Override
public User findById(final long id) {
public User findById(final long id) throws SQLException {
return userDao.findById(id);
}

@Override
public void insert(final User user) {
public void insert(final User user) throws SQLException {
userDao.insert(user);
}

@Override
public void changePassword(long id, final String newPassword, final String createBy) {
public void changePassword(long id, final String newPassword, final String createBy) throws SQLException {
final var user = findById(id);
user.changePassword(newPassword);
userHistoryDao.log(new UserHistory(user, createBy));
userDao.update(user);
userHistoryDao.log(new UserHistory(user, createBy));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.techcourse.service;

import java.sql.SQLException;

@FunctionalInterface
public interface TransactionCallback<T> {

T execute() throws SQLException;
}
65 changes: 65 additions & 0 deletions app/src/main/java/com/techcourse/service/TransactionManager.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package com.techcourse.service;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.transaction.support.TransactionSynchronizationManager;

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

public class TransactionManager {

private final DataSource dataSource;

public TransactionManager(final DataSource dataSource) {
this.dataSource = dataSource;
}

public <T> T execute(final TransactionCallback<T> callback) {
try {
final Connection connection = TransactionSynchronizationManager.startNewTransaction(dataSource);

final T result = callback.execute();

commitTransaction(connection);
TransactionSynchronizationManager.finishTransaction(dataSource);

return result;
} catch (final SQLException ex) {
throw new RuntimeException("실행 중 예외가 발생했습니다.");
}
}

public static void commitTransaction(final Connection connection) {
try {
connection.commit();

clear(connection);
} catch (final SQLException ex) {
rollback(connection);

throw new DataAccessException("실행 중 예외가 발생했습니다.");
}
}
Comment on lines +19 to +44
Copy link

Choose a reason for hiding this comment

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

P2. finally 블록을 이용해, callback.execute(); 에서 예외가 발생했을 때에도 rollback을 시켜주는 건 어떨까요?
지금은 commit을 호출했을 때의 예외에 대해서만 rollback을 시켜주는 것 같아요!


public static void rollback(final Connection connection) {
try {
connection.rollback();

clear(connection);
} catch (final SQLException ex) {
throw new DataAccessException("트랜잭션 롤백 중 예외가 발생했습니다.");
}
}

private static void clear(final Connection connection) {
try {
connection.setAutoCommit(true);
connection.close();
DataSourceUtils.releaseConnection(connection);
} catch (final SQLException ex) {
throw new DataAccessException("커넥션 종료 중 예외가 발생했습니다.");
}
}
}
31 changes: 12 additions & 19 deletions app/src/main/java/com/techcourse/service/TxUserService.java
Original file line number Diff line number Diff line change
@@ -1,42 +1,35 @@
package com.techcourse.service;

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

public class TxUserService implements UserService {

private final AppUserService userService;
private final TransactionManager transactionManager;

public TxUserService(final AppUserService userService) {
public TxUserService(final AppUserService userService, final TransactionManager transactionManager) {
this.userService = userService;
this.transactionManager = transactionManager;
}

@Override
public User findById(final long id) {
TransactionSynchronizationManager.startTransaction();

final User findUser = userService.findById(id);

TransactionSynchronizationManager.finishTransaction();

return findUser;
return transactionManager.execute(() -> userService.findById(id));
}

@Override
public void insert(final User user) {
TransactionSynchronizationManager.startTransaction();

userService.insert(user);

TransactionSynchronizationManager.finishTransaction();
transactionManager.execute(() -> {
userService.insert(user);
return null;
});
}

@Override
public void changePassword(final long id, final String newPassword, final String createBy) {
TransactionSynchronizationManager.startTransaction();

userService.changePassword(id, newPassword, createBy);

TransactionSynchronizationManager.finishTransaction();
transactionManager.execute(() -> {
userService.changePassword(id, newPassword, createBy);
return null;
});
}
}
8 changes: 5 additions & 3 deletions app/src/main/java/com/techcourse/service/UserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@

import com.techcourse.domain.User;

import java.sql.SQLException;

public interface UserService {

User findById(final long id);
User findById(final long id) throws SQLException;

void insert(final User user);
void insert(final User user) throws SQLException;

void changePassword(final long id, final String newPassword, final String createBy);
void changePassword(final long id, final String newPassword, final String createBy) throws SQLException;
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;

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

import static org.assertj.core.api.Assertions.assertThat;
Expand All @@ -25,13 +26,14 @@ void setUp() throws SQLException {
this.jdbcTemplate = new JdbcTemplate(DataSourceConfig.getInstance());
this.userDao = new UserDao(jdbcTemplate);

DatabasePopulatorUtils.execute(DataSourceConfig.getInstance());
final DataSource dataSource = DataSourceConfig.getInstance();
DatabasePopulatorUtils.execute(dataSource);
final var user = new User("gugu", "password", "[email protected]");
userDao.insert(user);
}

@Test
void testChangePassword() {
void testChangePassword() throws SQLException {
final var userHistoryDao = new UserHistoryDao(jdbcTemplate);
final var userService = new AppUserService(userDao, userHistoryDao);

Expand All @@ -51,7 +53,8 @@ void testTransactionRollback() {
// 애플리케이션 서비스
final var appUserService = new AppUserService(userDao, userHistoryDao);
// 트랜잭션 서비스 추상화
final var userService = new TxUserService(appUserService);
final var transactionManager = new TransactionManager(DataSourceConfig.getInstance());
final var userService = new TxUserService(appUserService, transactionManager);

final var newPassword = "newPassword";
final var createBy = "gugu";
Expand Down
34 changes: 17 additions & 17 deletions jdbc/src/main/java/org/springframework/jdbc/core/JdbcTemplate.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.CannotGetJdbcConnectionException;
import org.springframework.dao.DataAccessException;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.sql.DataSource;
Expand All @@ -25,20 +25,20 @@ public JdbcTemplate(final DataSource dataSource) {
this.dataSource = dataSource;
}

public <T> Optional<T> queryForObject(final String sql, final RowMapper<T> rowMapper, final Object... parameters) {
public <T> Optional<T> queryForObject(final String sql, final RowMapper<T> rowMapper, final Object... parameters) throws SQLException {
return execute(sql, preparedStatement -> {
final ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
return Optional.of(rowMapper.mapRow(resultSet));
}
if (!resultSet.isLast()) {
throw new RuntimeException("단일 데이터가 아닙니다.");
throw new DataAccessException("단일 데이터가 아닙니다.");
}
return Optional.empty();
}, parameters);
}

public <T> List<T> query(final String sql, final RowMapper<T> rowMapper) {
public <T> List<T> query(final String sql, final RowMapper<T> rowMapper) throws SQLException {
return execute(sql, preparedStatement -> {
final ResultSet resultSet = preparedStatement.executeQuery();
final List<T> objects = new ArrayList<>();
Expand All @@ -50,24 +50,24 @@ public <T> List<T> query(final String sql, final RowMapper<T> rowMapper) {
});
}

public int update(final String sql, final Object... parameters) {
public int update(final String sql, final Object... parameters) throws SQLException {
return execute(sql, PreparedStatement::executeUpdate, parameters);
}

public <T> T execute(final String sql, final ExecuteQueryCallback<T> callBack, final Object... objects) {
try {
final Connection connection = TransactionSynchronizationManager.getResource(dataSource);
final PreparedStatement preparedStatement = connection.prepareStatement(sql);
public <T> T execute(
final String sql,
final ExecuteQueryCallback<T> callBack,
final Object... objects
) throws SQLException {
final PreparedStatement preparedStatement = createPreparedStatement(sql);
setPreparedStatement(preparedStatement, objects);

setPreparedStatement(preparedStatement, objects);

return TransactionSynchronizationManager.commit(callBack, preparedStatement, dataSource);
} catch (SQLException ex) {
TransactionSynchronizationManager.rollback(dataSource);
return callBack.execute(preparedStatement);
}

log.error(ex.getMessage());
throw new CannotGetJdbcConnectionException("jdbc 연결에 실패했습니다.");
}
private PreparedStatement createPreparedStatement(final String sql) throws SQLException {
final Connection connection = TransactionSynchronizationManager.getResource(dataSource);
return connection.prepareStatement(sql);
}
Copy link

Choose a reason for hiding this comment

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

P3. TxUserService가 아닌 AppUserService의 메서드를 호출한다면, connection이 계속 열려있지 않을까요?


private void setPreparedStatement(final PreparedStatement preparedStatement, final Object[] parameters) throws SQLException {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package org.springframework.jdbc.datasource;

import org.springframework.jdbc.CannotGetJdbcConnectionException;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.sql.DataSource;
import java.sql.Connection;
Expand All @@ -12,18 +11,17 @@ public abstract class DataSourceUtils {
private DataSourceUtils() {
}

public static Connection getConnection(DataSource dataSource) throws CannotGetJdbcConnectionException, SQLException {
public static Connection getConnection(final DataSource dataSource) throws CannotGetJdbcConnectionException, SQLException {
try {
return TransactionSynchronizationManager.getResource(dataSource);
return dataSource.getConnection();
} catch (SQLException ex) {
throw new CannotGetJdbcConnectionException("Failed to obtain JDBC Connection", ex);
}
}

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