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단계] 디투(박정훈) 미션 제출합니다. #593

Merged
merged 6 commits into from
Oct 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
9 changes: 5 additions & 4 deletions app/src/main/java/com/techcourse/dao/UserDao.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.techcourse.domain.User;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetMapper;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.sql.DataSource;
import java.sql.Connection;
Expand All @@ -23,14 +24,14 @@ public UserDao(final DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}

public void insert(final Connection connection, final User user) {
public void insert(final User user) {
final String sql = "insert into users (account, password, email) values (?, ?, ?)";
jdbcTemplate.update(connection, sql, user.getAccount(), user.getPassword(), user.getEmail());
jdbcTemplate.update(sql, user.getAccount(), user.getPassword(), user.getEmail());
}

public void update(final Connection connection, final User user) {
public void update(final User user) {
final String sql = "update users set account = ?, password = ?, email = ? where id = ?";
jdbcTemplate.update(connection, sql, user.getAccount(), user.getPassword(), user.getEmail(), user.getId());
jdbcTemplate.update(sql, user.getAccount(), user.getPassword(), user.getEmail(), user.getId());
}

public List<User> findAll() {
Expand Down
35 changes: 11 additions & 24 deletions app/src/main/java/com/techcourse/dao/UserHistoryDao.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,34 +12,21 @@

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;
}

public UserHistoryDao(final JdbcTemplate jdbcTemplate) {
this.dataSource = null;
this.jdbcTemplate = new JdbcTemplate(dataSource);
}

public void log(final Connection connection, final UserHistory userHistory) {
public void log(final UserHistory userHistory) {
final var sql = "insert into user_history (user_id, account, password, email, created_at, created_by) values (?, ?, ?, ?, ?, ?)";

try (final PreparedStatement pstmt = connection.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);
}
jdbcTemplate.update(sql,
userHistory.getUserId(),
userHistory.getAccount(),
userHistory.getPassword(),
userHistory.getEmail(),
userHistory.getCreatedAt(),
userHistory.getCreateBy()
);
}
}
35 changes: 35 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,35 @@
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;
}

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

@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));
}
}
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.transaction.support.TransactionTemplate;

public class TxUserService implements UserService {

private final AppUserService appUserService;
private final TransactionTemplate transactionTemplate;

public TxUserService(final AppUserService appUserService, final TransactionTemplate transactionTemplate) {
this.appUserService = appUserService;
this.transactionTemplate = transactionTemplate;
}

@Override
public User findById(final long id) {
return appUserService.findById(id);
}

@Override
public void insert(final User user) {
transactionTemplate.execute(connection -> appUserService.insert(user));
}

@Override
public void changePassword(final long id, final String newPassword, final String createBy) {
transactionTemplate.execute(connection -> appUserService.changePassword(id, newPassword, createBy));
}
}
83 changes: 4 additions & 79 deletions app/src/main/java/com/techcourse/service/UserService.java
Original file line number Diff line number Diff line change
@@ -1,85 +1,10 @@
package com.techcourse.service;

import com.techcourse.config.DataSourceConfig;
import com.techcourse.dao.UserDao;
import com.techcourse.dao.UserHistoryDao;
import com.techcourse.domain.User;
import com.techcourse.domain.UserHistory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;

import java.sql.Connection;
import java.sql.SQLException;
public interface UserService {

public class UserService {

private static final Logger log = LoggerFactory.getLogger(UserService.class);

private final UserDao userDao;
private final UserHistoryDao userHistoryDao;

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) {
Connection connection = null;
try {
connection = DataSourceConfig.getInstance().getConnection();
connection.setAutoCommit(false);
userDao.insert(connection, user);
connection.commit();
} catch (SQLException e) {
log.error(e.getMessage());
rollback(connection);
} finally {
release(connection);
}
}

public void changePassword(final long id, final String newPassword, final String createBy) {
Connection connection = null;
try {
connection = DataSourceConfig.getInstance().getConnection();
connection.setAutoCommit(false);
final var user = findById(id);
user.changePassword(newPassword);
userDao.update(connection, user);
userHistoryDao.log(connection, new UserHistory(user, createBy));
connection.commit();
} catch (SQLException e) {
log.error(e.getMessage());
rollback(connection);
} finally {
release(connection);
}
}

private void rollback(final Connection connection) {
if (connection != null) {
try {
connection.rollback();
} catch (SQLException e) {
log.error(e.getMessage());
throw new DataAccessException("rollback 에 실패했습니다.");
}
}
}

private void release(final Connection connection) {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
log.error(e.getMessage());
throw new DataAccessException("자원 정리에 실패했습니다.");
}
}
}
User findById(final long id);
void insert(final User user);
void changePassword(final long id, final String newPassword, final String createBy);
}
12 changes: 6 additions & 6 deletions app/src/test/java/com/techcourse/dao/UserDaoTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ void setup() throws SQLException {
userDao = new UserDao(dataSource);
connection = dataSource.getConnection();
final var user = new User("hongsil", "486", "[email protected]");
userDao.insert(connection, user);
userDao.insert(user);
}

@Test
Expand All @@ -54,7 +54,7 @@ void findById_make_exception_when_no_result() {
@Test
void findByAccount() {
final var account = "mylove_hongsil";
userDao.insert(connection, new User(account, "비밀번호486", "[email protected]"));
userDao.insert(new User(account, "비밀번호486", "[email protected]"));
final var user = userDao.findByAccount(account);

assertThat(user.getAccount()).isEqualTo(account);
Expand All @@ -63,8 +63,8 @@ void findByAccount() {
@Test
void findByAccount_make_exception_when_multiple_result() {
final var user = new User("ditoo", "password", "[email protected]");
userDao.insert(connection, user);
userDao.insert(connection, user);
userDao.insert(user);
userDao.insert(user);
assertThatThrownBy(() -> userDao.findByAccount(user.getAccount()))
.isInstanceOf(IncorrectResultSizeDataAccessException.class);
}
Expand All @@ -73,7 +73,7 @@ void findByAccount_make_exception_when_multiple_result() {
void insert() {
final var account = "insert-gugu";
final var user = new User(account, "password", "[email protected]");
userDao.insert(connection, user);
userDao.insert(user);

final var actual = userDao.findById(2L);

Expand All @@ -86,7 +86,7 @@ void update() {
final var user = userDao.findById(1L);
user.changePassword(newPassword);

userDao.update(connection, user);
userDao.update(user);

final var actual = userDao.findById(1L);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,17 @@
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;

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

public class MockUserHistoryDao extends UserHistoryDao {

public MockUserHistoryDao(final JdbcTemplate jdbcTemplate) {
super(jdbcTemplate);
public MockUserHistoryDao(final DataSource dataSource) {
super(dataSource);
}

@Override
public void log(final Connection connection, final UserHistory userHistory) {
public void log(final UserHistory userHistory) {
throw new DataAccessException();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,61 +6,64 @@
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.transaction.support.TransactionTemplate;

import javax.sql.DataSource;

import java.sql.SQLException;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.spy;

class UserServiceTest {
class TxUserServiceTest {

private JdbcTemplate jdbcTemplate;
private DataSource dataSource;
private UserDao userDao;
private AppUserService appUserService;
private TransactionTemplate transactionTemplate;

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

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

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

final var newPassword = "qqqqq";
final var createBy = "gugu";
userService.changePassword(1L, newPassword, createBy);
appUserService.changePassword(1L, newPassword, createBy);

final var actual = userService.findById(1L);
final var actual = txUserService.findById(1L);

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

@Test
void testTransactionRollback() {
// 트랜잭션 롤백 테스트를 위해 mock으로 교체
final var userHistoryDao = new MockUserHistoryDao(jdbcTemplate);
final var userService = new UserService(userDao, userHistoryDao);
final AppUserService appUserService = new AppUserService(userDao, new MockUserHistoryDao(dataSource));
final var txUserService = new TxUserService(appUserService, transactionTemplate);

final var newPassword = "newPassword";
final var createBy = "gugu";
// 트랜잭션이 정상 동작하는지 확인하기 위해 의도적으로 MockUserHistoryDao에서 예외를 발생시킨다.
assertThrows(DataAccessException.class,
() -> userService.changePassword(1L, newPassword, createBy));
() -> txUserService.changePassword(1L, newPassword, createBy));

final var actual = userService.findById(1L);
final var actual = txUserService.findById(1L);

assertThat(actual.getPassword()).isNotEqualTo(newPassword);
}
Expand Down
Loading
Loading