-
Notifications
You must be signed in to change notification settings - Fork 300
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
[3단계 - JDBC 라이브러리 구현하기] 페드로(류형욱) 미션 제출합니다. #850
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
411c0f0
chore(UserServiceTest): 테스트 코드의 `@Disabled` 삭제
hw0603 a36dfb8
feat(TransactionManager): 트랜잭션을 관리할 객체 생성
hw0603 3fca6b3
feat(UserService): 사용자 비밀번호 변경 로직에 트랜잭션 적용
hw0603 21d24e3
refactor(JdbcTemplate): 오버로딩된 update() 메서드의 호출 계층 구조 설정
hw0603 84c362c
style(JdbcTemplate): 메서드 순서 변경
hw0603 f4d4e64
refactor(ThrowingConsumer): 인터페이스 선언 위치 변경
hw0603 ce08eb9
refactor(JdbcTemplate): update 메서드의 시그니처 추가 지원
hw0603 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,32 +1,40 @@ | ||
package com.techcourse.service; | ||
|
||
import com.interface21.jdbc.transaction.TransactionManager; | ||
import com.techcourse.dao.UserDao; | ||
import com.techcourse.dao.UserHistoryDao; | ||
import com.techcourse.domain.User; | ||
import com.techcourse.domain.UserHistory; | ||
import java.sql.Connection; | ||
|
||
public class UserService { | ||
|
||
private final TransactionManager txManager; | ||
private final UserDao userDao; | ||
private final UserHistoryDao userHistoryDao; | ||
|
||
public UserService(final UserDao userDao, final UserHistoryDao userHistoryDao) { | ||
public UserService(TransactionManager txManager, UserDao userDao, UserHistoryDao userHistoryDao) { | ||
this.txManager = txManager; | ||
this.userDao = userDao; | ||
this.userHistoryDao = userHistoryDao; | ||
} | ||
|
||
public User findById(final long id) { | ||
public User findById(long id) { | ||
return userDao.findById(id); | ||
} | ||
|
||
public void insert(final User user) { | ||
public void insert(User user) { | ||
userDao.insert(user); | ||
} | ||
|
||
public void changePassword(final long id, final String newPassword, final String createBy) { | ||
public void changePassword(long id, String newPassword, String createBy) { | ||
txManager.executeTransactionOf(conn -> changePasswordTx(conn, id, newPassword, createBy)); | ||
} | ||
|
||
private void changePasswordTx(Connection connection, long id, String newPassword, String createBy) { | ||
final var user = findById(id); | ||
user.changePassword(newPassword); | ||
userDao.update(user); | ||
userHistoryDao.log(new UserHistory(user, createBy)); | ||
userDao.updateUsingExplicitConnection(user, connection); | ||
userHistoryDao.logUsingExplicitConnection(new UserHistory(user, createBy), connection); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
26 changes: 26 additions & 0 deletions
26
jdbc/src/main/java/com/interface21/jdbc/core/QueryConnectionHolder.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
package com.interface21.jdbc.core; | ||
|
||
import com.interface21.dao.DataAccessException; | ||
import java.sql.Connection; | ||
import java.sql.PreparedStatement; | ||
import java.sql.SQLException; | ||
import java.util.Objects; | ||
|
||
public class QueryConnectionHolder { | ||
|
||
private final String query; | ||
private final Connection connection; | ||
|
||
public QueryConnectionHolder(Connection connection, String query) { | ||
this.connection = Objects.requireNonNull(connection); | ||
this.query = Objects.requireNonNull(query); | ||
} | ||
|
||
public PreparedStatement getAsPreparedStatement() { | ||
try { | ||
return connection.prepareStatement(query); | ||
} catch (SQLException e) { | ||
throw new DataAccessException("PreparedStatement 생성 실패", e); | ||
} | ||
} | ||
} |
53 changes: 53 additions & 0 deletions
53
jdbc/src/main/java/com/interface21/jdbc/transaction/TransactionManager.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
package com.interface21.jdbc.transaction; | ||
|
||
import com.interface21.dao.DataAccessException; | ||
import java.sql.Connection; | ||
import java.sql.SQLException; | ||
import java.util.logging.Logger; | ||
import javax.sql.DataSource; | ||
|
||
public class TransactionManager { | ||
|
||
private static final Logger log = Logger.getLogger(TransactionManager.class.getName()); | ||
|
||
private final DataSource dataSource; | ||
|
||
public TransactionManager(DataSource dataSource) { | ||
this.dataSource = dataSource; | ||
} | ||
|
||
public void executeTransactionOf(TransactionalFunction callback) { | ||
Connection connection = null; | ||
boolean shouldThrow = false; | ||
try { | ||
connection = dataSource.getConnection(); | ||
connection.setAutoCommit(false); | ||
callback.execute(connection); | ||
connection.commit(); | ||
} catch (Exception e) { | ||
gracefulShutdown(connection, Connection::rollback); | ||
shouldThrow = true; | ||
} finally { | ||
gracefulShutdown(connection, Connection::close); | ||
} | ||
if (shouldThrow) { | ||
throw new DataAccessException("트랜잭션 실행 중 문제가 발생했습니다. 트랜잭션은 롤백됩니다."); | ||
} | ||
} | ||
|
||
private void gracefulShutdown(Connection connection, ThrowingConsumer<Connection> connectionConsumer) { | ||
try { | ||
connectionConsumer.accept(connection); | ||
} catch (NullPointerException e) { | ||
log.warning("Connection을 찾을 수 없습니다."); | ||
} catch (SQLException e) { | ||
throw new DataAccessException(e.getMessage(), e); | ||
} | ||
} | ||
|
||
@FunctionalInterface | ||
private interface ThrowingConsumer<T> { | ||
|
||
void accept(T connection) throws SQLException; | ||
} | ||
} |
10 changes: 10 additions & 0 deletions
10
jdbc/src/main/java/com/interface21/jdbc/transaction/TransactionalFunction.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
package com.interface21.jdbc.transaction; | ||
|
||
import java.sql.Connection; | ||
import java.sql.SQLException; | ||
|
||
@FunctionalInterface | ||
public interface TransactionalFunction { | ||
|
||
void execute(Connection connection) throws SQLException; | ||
} | ||
57 changes: 57 additions & 0 deletions
57
jdbc/src/test/java/com/interface21/jdbc/transaction/TransactionManagerTest.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
package com.interface21.jdbc.transaction; | ||
|
||
import static org.assertj.core.api.Assertions.assertThatThrownBy; | ||
import static org.mockito.BDDMockito.given; | ||
import static org.mockito.Mockito.mock; | ||
import static org.mockito.Mockito.never; | ||
import static org.mockito.Mockito.verify; | ||
|
||
import com.interface21.dao.DataAccessException; | ||
import java.sql.Connection; | ||
import java.sql.SQLException; | ||
import javax.sql.DataSource; | ||
import org.junit.jupiter.api.BeforeEach; | ||
import org.junit.jupiter.api.DisplayName; | ||
import org.junit.jupiter.api.Test; | ||
|
||
class TransactionManagerTest { | ||
|
||
private DataSource dataSource; | ||
private Connection connection; | ||
|
||
@BeforeEach | ||
void setUp() throws SQLException { | ||
dataSource = mock(DataSource.class); | ||
connection = mock(Connection.class); | ||
given(dataSource.getConnection()).willReturn(connection); | ||
} | ||
|
||
@Test | ||
@DisplayName("트랜잭션 실행 중 예외가 발생하면 롤백된다.") | ||
void rollbackOnException() throws SQLException { | ||
// given | ||
TransactionManager txManager = new TransactionManager(dataSource); | ||
TransactionalFunction txFunction = conn -> { | ||
throw new SQLException(); | ||
}; | ||
|
||
// when & then | ||
assertThatThrownBy(() -> txManager.executeTransactionOf(txFunction)) | ||
.isInstanceOf(DataAccessException.class); | ||
verify(connection).rollback(); | ||
verify(connection, never()).commit(); | ||
verify(connection).close(); | ||
} | ||
|
||
@Test | ||
@DisplayName("예외 없는 트랜잭션은 정상적으로 커밋된다.") | ||
void commitOnNoException() throws SQLException { | ||
TransactionManager txManager = new TransactionManager(dataSource); | ||
TransactionalFunction txFunction = conn -> {}; | ||
txManager.executeTransactionOf(txFunction); | ||
|
||
verify(connection).commit(); | ||
verify(connection, never()).rollback(); | ||
verify(connection).close(); | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Consumer 역할로 보이는데 Function이라는 클래스명은 혼동을 줄 수 있을 것 같아요! (ThrowingConsumer도 있기 때문에)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
그럴 수도 있겠네요!
사실
ThrowingConsumer
보다는TransactionalFunction
이 더 중요한 역할을 하는데요,ThrowingConsumer<T, E>
형태로 예외를 던지면서 consume 하는 전역 인터페이스를 만들어서 사용하려는 것이 의도였는데 지금은 사실 던질 수 있는 예외가SQLException
으로 고정되어 있고TransactionManager
에서만 사용하다 보니 굳이 클래스 외부에 있을 필요가 없을 것 같네요.ThrowingConsumer
인터페이스 선언 위치를TransactionManager
내부로 변경하였습니다.TransactionalFunction
인터페이스는 그대로 유지할게요!