-
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
[JDBC 라이브러리 구현하기 - 3,4단계] 도치(김동흠) 미션 제출합니다. #529
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
bd71827
feat:비밀번호 변경과 로깅에 대한 트랜잭션 구현
hum02 3433bb4
feat:Transaction synchronization 적용
hum02 064bb27
refactor:dataSourceUtils로 conection받아 트랜잭션 처리하도록 수정
hum02 31ff2b1
refactor:TxUserService로 트랜잭션 로직 분리
hum02 7e93cb3
feat:deleteAll과 insert한 터플id 리턴하는 메서드 구현
hum02 2aef506
refactor:중복된 커넥션 close삭제
hum02 b4e29bd
feat:유저의 findById,insert메서드에 트랜잭션 적용
hum02 12c061f
refactor(TransactionSynchronizationManager):key에 맞는 값 없을 시 null반환함을 명…
hum02 171a26d
refactor:unbind시 connection close확인 후 unbind하도록 수정
hum02 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,62 +1,31 @@ | ||
package com.techcourse.dao; | ||
|
||
import com.techcourse.domain.UserHistory; | ||
import org.springframework.jdbc.core.JdbcTemplate; | ||
import org.slf4j.Logger; | ||
import org.slf4j.LoggerFactory; | ||
import org.springframework.jdbc.core.JdbcTemplate; | ||
|
||
import javax.sql.DataSource; | ||
import java.sql.Connection; | ||
import java.sql.PreparedStatement; | ||
import java.sql.SQLException; | ||
|
||
public class UserHistoryDao { | ||
|
||
private static final Logger log = LoggerFactory.getLogger(UserHistoryDao.class); | ||
|
||
private final DataSource dataSource; | ||
private final JdbcTemplate jdbcTemplate; | ||
|
||
public UserHistoryDao(final DataSource dataSource) { | ||
this.dataSource = dataSource; | ||
this.jdbcTemplate = new JdbcTemplate(dataSource); | ||
} | ||
|
||
public UserHistoryDao(final JdbcTemplate jdbcTemplate) { | ||
this.dataSource = null; | ||
this.jdbcTemplate = jdbcTemplate; | ||
} | ||
|
||
public void log(final UserHistory userHistory) { | ||
final var sql = "insert into user_history (user_id, account, password, email, created_at, created_by) values (?, ?, ?, ?, ?, ?)"; | ||
|
||
Connection conn = null; | ||
PreparedStatement pstmt = null; | ||
try { | ||
conn = dataSource.getConnection(); | ||
pstmt = conn.prepareStatement(sql); | ||
|
||
log.debug("query : {}", sql); | ||
|
||
pstmt.setLong(1, userHistory.getUserId()); | ||
pstmt.setString(2, userHistory.getAccount()); | ||
pstmt.setString(3, userHistory.getPassword()); | ||
pstmt.setString(4, userHistory.getEmail()); | ||
pstmt.setObject(5, userHistory.getCreatedAt()); | ||
pstmt.setString(6, userHistory.getCreateBy()); | ||
pstmt.executeUpdate(); | ||
} catch (SQLException e) { | ||
log.error(e.getMessage(), e); | ||
throw new RuntimeException(e); | ||
} finally { | ||
try { | ||
if (pstmt != null) { | ||
pstmt.close(); | ||
} | ||
} catch (SQLException ignored) {} | ||
|
||
try { | ||
if (conn != null) { | ||
conn.close(); | ||
} | ||
} catch (SQLException ignored) {} | ||
} | ||
final var sql = "insert into user_history (user_id, account, password, email, created_at, created_by) " + | ||
"values (?, ?, ?, ?, ?, ?)"; | ||
|
||
jdbcTemplate.update(sql, userHistory.getUserId(), userHistory.getAccount(), userHistory.getPassword(), | ||
userHistory.getEmail(), userHistory.getCreatedAt(), userHistory.getCreateBy()); | ||
} | ||
} |
36 changes: 36 additions & 0 deletions
36
app/src/main/java/com/techcourse/service/AppUserService.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,36 @@ | ||
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(UserDao userDao, UserHistoryDao userHistoryDao) { | ||
this.userDao = userDao; | ||
this.userHistoryDao = userHistoryDao; | ||
} | ||
|
||
@Override | ||
public User findById(final long id) { | ||
return userDao.findById(id) | ||
.orElseThrow(() -> new IllegalArgumentException("해당 아이디의 회원이 존재하지 않습니다.")); | ||
} | ||
|
||
@Override | ||
public void insert(final User user) { | ||
userDao.insert(user); | ||
} | ||
|
||
@Override | ||
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)); | ||
} | ||
} |
32 changes: 32 additions & 0 deletions
32
app/src/main/java/com/techcourse/service/TxUserService.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,32 @@ | ||
package com.techcourse.service; | ||
|
||
import com.techcourse.config.DataSourceConfig; | ||
import com.techcourse.domain.User; | ||
import org.springframework.transaction.support.TransactionHandler; | ||
|
||
public class TxUserService implements UserService { | ||
|
||
private final UserService userService; | ||
private final TransactionHandler transactionHandler; | ||
|
||
public TxUserService(final UserService userService) { | ||
this.userService = userService; | ||
this.transactionHandler = new TransactionHandler(DataSourceConfig.getInstance()); | ||
} | ||
|
||
@Override | ||
public User findById(long id) { | ||
return transactionHandler.handle(() -> userService.findById(id)); | ||
} | ||
|
||
@Override | ||
public void insert(User user) { | ||
transactionHandler.handle(() -> userService.insert(user)); | ||
} | ||
|
||
@Override | ||
public void changePassword(final long id, final String newPassword, final String createBy) { | ||
transactionHandler.handle(() -> userService.changePassword(id, newPassword, createBy)); | ||
} | ||
} | ||
|
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,33 +1,12 @@ | ||
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 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) | ||
.orElseThrow(() -> new IllegalArgumentException("해당 아이디의 회원이 존재하지 않습니다.")); | ||
} | ||
|
||
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)); | ||
} | ||
void changePassword(final long id, final String newPassword, final String createBy); | ||
} |
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,6 +1,6 @@ | ||
create table if not exists users ( | ||
id bigint auto_increment, | ||
account varchar(100) not null, | ||
account varchar(100) not null unique, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 👍 |
||
password varchar(100) not null, | ||
email varchar(100) not null, | ||
primary key(id) | ||
|
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 |
---|---|---|
|
@@ -6,21 +6,20 @@ | |
import org.junit.jupiter.api.BeforeEach; | ||
import org.junit.jupiter.api.Test; | ||
|
||
import java.util.List; | ||
|
||
import static org.assertj.core.api.Assertions.assertThat; | ||
|
||
class UserDaoTest { | ||
|
||
private UserDao userDao; | ||
private long userId; | ||
|
||
@BeforeEach | ||
void setup() { | ||
DatabasePopulatorUtils.execute(DataSourceConfig.getInstance()); | ||
|
||
userDao = new UserDao(DataSourceConfig.getInstance()); | ||
userDao.deleteAll(); | ||
final var user = new User("gugu", "password", "[email protected]"); | ||
userDao.insert(user); | ||
userId = userDao.insert(user); | ||
} | ||
|
||
@Test | ||
|
@@ -32,26 +31,26 @@ void findAll() { | |
|
||
@Test | ||
void findById() { | ||
final var user = userDao.findById(1L).get(); | ||
final var user = userDao.findById(userId).get(); | ||
|
||
assertThat(user.getAccount()).isEqualTo("gugu"); | ||
} | ||
|
||
@Test | ||
void findByAccount() { | ||
final var account = "gugu"; | ||
List<User> users = userDao.findByAccount(account); | ||
User user = userDao.findByAccount(account).get(); | ||
|
||
assertThat(users).extracting("account").containsOnly("gugu"); | ||
assertThat(user.getAccount()).isEqualTo("gugu"); | ||
} | ||
|
||
@Test | ||
void insert() { | ||
final var account = "insert-gugu"; | ||
final var user = new User(account, "password", "[email protected]"); | ||
userDao.insert(user); | ||
long insertedId = userDao.insert(user); | ||
|
||
final var actual = userDao.findById(2L).get(); | ||
final var actual = userDao.findById(insertedId).get(); | ||
|
||
assertThat(actual.getAccount()).isEqualTo(account); | ||
assertThat(actual.getEmail()).isEqualTo("[email protected]"); | ||
|
@@ -60,12 +59,12 @@ void insert() { | |
@Test | ||
void update() { | ||
final var newPassword = "password99"; | ||
final var user = userDao.findById(1L).get(); | ||
final var user = userDao.findById(userId).get(); | ||
user.changePassword(newPassword); | ||
|
||
userDao.update(user); | ||
|
||
final var actual = userDao.findById(1L).get(); | ||
final var actual = userDao.findById(userId).get(); | ||
|
||
assertThat(actual.getPassword()).isEqualTo(newPassword); | ||
} | ||
|
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 |
---|---|---|
|
@@ -5,41 +5,43 @@ | |
import com.techcourse.dao.UserHistoryDao; | ||
import com.techcourse.domain.User; | ||
import com.techcourse.support.jdbc.init.DatabasePopulatorUtils; | ||
import org.springframework.dao.DataAccessException; | ||
import org.springframework.jdbc.core.JdbcTemplate; | ||
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 static org.assertj.core.api.Assertions.assertThat; | ||
import static org.junit.jupiter.api.Assertions.assertThrows; | ||
|
||
@Disabled | ||
class UserServiceTest { | ||
|
||
private JdbcTemplate jdbcTemplate; | ||
private UserDao userDao; | ||
private long userId; | ||
|
||
@BeforeEach | ||
void setUp() { | ||
this.jdbcTemplate = new JdbcTemplate(DataSourceConfig.getInstance()); | ||
final var dataSource = DataSourceConfig.getInstance(); | ||
this.jdbcTemplate = new JdbcTemplate(dataSource); | ||
this.userDao = new UserDao(jdbcTemplate); | ||
|
||
DatabasePopulatorUtils.execute(DataSourceConfig.getInstance()); | ||
userDao.deleteAll(); | ||
final var user = new User("gugu", "password", "[email protected]"); | ||
userDao.insert(user); | ||
userId = userDao.insert(user); | ||
} | ||
|
||
@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"; | ||
userService.changePassword(1L, newPassword, createBy); | ||
|
||
final var actual = userService.findById(1L); | ||
userService.changePassword(userId, newPassword, createBy); | ||
|
||
final var actual = userService.findById(userId); | ||
|
||
assertThat(actual.getPassword()).isEqualTo(newPassword); | ||
} | ||
|
@@ -48,15 +50,18 @@ 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)); | ||
() -> userService.changePassword(userId, newPassword, createBy)); | ||
|
||
final var actual = userService.findById(1L); | ||
final var actual = userService.findById(userId); | ||
|
||
assertThat(actual.getPassword()).isNotEqualTo(newPassword); | ||
} | ||
|
Oops, something went wrong.
Oops, something went wrong.
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.
findById랑 insert에는 트랜잭션을 적용하지 않은 이유가 있을까요?
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.
여기도 트랜잭션 적용하는 게 좋을 것 같아요!