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단계] 주디(오은비) 미션 제출합니다. #596

Merged
merged 18 commits into from
Oct 13, 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
5 changes: 0 additions & 5 deletions app/src/main/java/com/techcourse/dao/UserDao.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,6 @@ public void update(final User user) {
jdbcTemplate.update(sql, user.getPassword(), user.getEmail(), user.getAccount(), user.getId());
}

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

public List<User> findAll() {
final var sql = "select id, account, password, email from users";
return jdbcTemplate.query(sql, USER_ROW_MAPPER);
Expand Down
6 changes: 0 additions & 6 deletions app/src/main/java/com/techcourse/dao/UserHistoryDao.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,6 @@ public UserHistoryDao(final JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}

public void log(final Connection connection, final UserHistory userHistory) {
final var sql = "insert into user_history (user_id, account, password, email, created_at, created_by) values (?, ?, ?, ?, ?, ?)";
jdbcTemplate.update(connection, sql, userHistory.getUserId(), userHistory.getAccount(), userHistory.getPassword(),
userHistory.getEmail(), userHistory.getCreatedAt(), userHistory.getCreateBy());
}

public void log(final UserHistory userHistory) {
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(),
Expand Down
36 changes: 36 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,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(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));
}

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

import com.techcourse.config.DataSourceConfig;
import com.techcourse.domain.User;
import java.sql.SQLException;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.datasource.DataSourceUtils;

public class TxUserService implements UserService {

private final UserService userService;

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

@Override
public User findById(final long id) {
User user;

final var dataSource = DataSourceConfig.getInstance();
final var connection = DataSourceUtils.getConnection(dataSource);
try {
connection.setAutoCommit(false);
user = userService.findById(id);

connection.commit();
} catch (final Exception e) {
try {
connection.rollback();
} catch (SQLException ex) {
throw new DataAccessException(ex);
}
throw new DataAccessException(e);
} finally {
DataSourceUtils.releaseConnection(connection, dataSource);
}

return user;
}

@Override
public void insert(final User user) {
final var dataSource = DataSourceConfig.getInstance();
final var connection = DataSourceUtils.getConnection(dataSource);
try {
connection.setAutoCommit(false);
userService.insert(user);

connection.commit();
} catch (final Exception e) {
try {
connection.rollback();
} catch (SQLException ex) {
throw new DataAccessException(ex);
}
throw new DataAccessException(e);
} finally {
DataSourceUtils.releaseConnection(connection, dataSource);
}
}

@Override
public void changePassword(final long id, final String newPassword, final String createBy) {
final var dataSource = DataSourceConfig.getInstance();
final var connection = DataSourceUtils.getConnection(dataSource);
try {
connection.setAutoCommit(false);
userService.changePassword(id, newPassword, createBy);

connection.commit();
} catch (final Exception e) {
try {
connection.rollback();
} catch (SQLException ex) {
throw new DataAccessException(ex);
}
throw new DataAccessException(e);
} finally {
DataSourceUtils.releaseConnection(connection, dataSource);
}
}
}
45 changes: 4 additions & 41 deletions app/src/main/java/com/techcourse/service/UserService.java
Original file line number Diff line number Diff line change
@@ -1,47 +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 java.sql.SQLException;
import org.springframework.dao.DataAccessException;

public class UserService {

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) {
userDao.insert(user);
}

public void changePassword(final long id, final String newPassword, final String createBy) throws SQLException {
final var connection = DataSourceConfig.getInstance().getConnection();
try {
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 (final Exception e) {
connection.rollback();
throw new DataAccessException(e);
} finally {
connection.close();
}
}
public interface UserService {

User findById(final long id);
void insert(final User user);
void changePassword(final long id, final String newPassword, final String createBy);
}
43 changes: 43 additions & 0 deletions app/src/test/java/com/techcourse/service/AppUserServiceTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
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.support.jdbc.init.DatabasePopulatorUtils;
import java.sql.SQLException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.jdbc.core.JdbcTemplate;

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

class AppUserServiceTest {

Choose a reason for hiding this comment

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

꼼꼼한 테스트 굿굿!! 👍🏻


private JdbcTemplate jdbcTemplate;
private UserDao userDao;

@BeforeEach
void setUp() {
this.jdbcTemplate = new JdbcTemplate(DataSourceConfig.getInstance());
this.userDao = new UserDao(jdbcTemplate);

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

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

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

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

assertThat(actual.getPassword()).isEqualTo(newPassword);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import com.techcourse.dao.UserHistoryDao;
import com.techcourse.domain.UserHistory;
import java.sql.Connection;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;

Expand All @@ -13,8 +12,8 @@ public MockUserHistoryDao(final JdbcTemplate jdbcTemplate) {
}

@Override
public void log(final Connection connection, final UserHistory userHistory) {
System.out.println("로그뜰까요아닐까용오오오");
Comment on lines -16 to -17

Choose a reason for hiding this comment

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

ㅋㅋㅋㅋㅋ여기 삭제 기록도 남네요

public void log(final UserHistory userHistory) {
throw new DataAccessException();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,17 @@

import com.techcourse.config.DataSourceConfig;
import com.techcourse.dao.UserDao;
import com.techcourse.dao.UserHistoryDao;
import com.techcourse.domain.User;
import com.techcourse.support.jdbc.init.DatabasePopulatorUtils;
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 java.sql.SQLException;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertThrows;

@Disabled
class UserServiceTest {
class TxUserServiceTest {

private JdbcTemplate jdbcTemplate;
private UserDao userDao;
Expand All @@ -32,37 +26,24 @@ void setUp() {
final var user = new User("gugu", "password", "[email protected]");
userDao.insert(user);
}

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

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

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

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

@Test
void testTransactionRollback() {
// 트랜잭션 롤백 테스트를 위해 mock으로 교체
// 트랜잭션이 정상 동작하는지 확인하기 위해 의도적으로 MockUserHistoryDao에서 예외를 발생시킨다.
final MockUserHistoryDao mockUserHistoryDao = new MockUserHistoryDao(jdbcTemplate);
final var userService = new UserService(userDao, mockUserHistoryDao);
final var userHistoryDao = new MockUserHistoryDao(jdbcTemplate);
// 애플리케이션 서비스
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));

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

assertAll(
() -> assertThrows(DataAccessException.class,
() -> userService.changePassword(1L, newPassword, createBy)),
() -> assertThat(actual.getPassword()).isNotEqualTo(newPassword)
);
assertThat(actual.getPassword()).isNotEqualTo(newPassword);
}

}
17 changes: 11 additions & 6 deletions jdbc/src/main/java/org/springframework/jdbc/core/JdbcTemplate.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import javax.sql.DataSource;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.SizeException;
import org.springframework.jdbc.datasource.DataSourceUtils;

public class JdbcTemplate {

Expand All @@ -29,7 +30,7 @@ public <T> T queryForObject(final String sql, final RowMapper<T> rowMapper, fina
throw new SizeException("too many result. expected 1 but was " + results.size());
}
if (results.isEmpty()) {
throw new SizeException("no result");
throw new DataAccessException("no result");
}
return results.get(0);
}
Expand All @@ -40,14 +41,14 @@ public <T> T queryForObject(final Connection connection, final String sql, final
throw new SizeException("too many result. expected 1 but was " + results.size());
}
if (results.isEmpty()) {
throw new SizeException("no result");
throw new DataAccessException("no result");
}
return results.get(0);
}

public <T> List<T> query(final String sql, final RowMapper<T> rowMapper, final Object... parameters) {
try (final Connection conn = dataSource.getConnection();
final PreparedStatement preparedStatement = conn.prepareStatement(sql);
final var conn = getConnection();
try (final PreparedStatement preparedStatement = conn.prepareStatement(sql);
final ResultSet resultSet = executeQuery(preparedStatement, parameters)) {
log.debug("query : {}", sql);
return mapResults(rowMapper, resultSet);
Expand Down Expand Up @@ -90,8 +91,8 @@ private <T> List<T> mapResults(final RowMapper<T> rowMapper, final ResultSet res
}

public void update(final String sql, final Object... parameters) {
try (final Connection conn = dataSource.getConnection();
final PreparedStatement preparedStatement = conn.prepareStatement(sql)) {
final Connection conn = getConnection();
try (final PreparedStatement preparedStatement = conn.prepareStatement(sql)) {
log.debug("query : {}", sql);

setParameters(preparedStatement, parameters);
Expand All @@ -114,4 +115,8 @@ public void update(final Connection conn, final String sql, final Object... para
}
}

private Connection getConnection() {
return DataSourceUtils.getConnection(dataSource);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ public static Connection getConnection(DataSource dataSource) throws CannotGetJd

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