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 라이브러리 구현하기 - 3,4단계] 호이(이건호) 미션 제출합니다. #603

Merged
merged 14 commits into from
Oct 12, 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
15 changes: 6 additions & 9 deletions app/src/main/java/com/techcourse/dao/UserDao.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,16 @@
import com.techcourse.domain.User;
import java.util.List;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

public class UserDao {

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

private static final RowMapper<User> USER_ROW_MAPPER = rs -> new User(rs.getLong(1), rs.getString(2),
rs.getString(3), rs.getString(4));
private static final RowMapper<User> USER_ROW_MAPPER = rs -> new User(
rs.getLong("id"),
rs.getString("account"),
rs.getString("password"),
rs.getString("email"));

Comment on lines +11 to 16

Choose a reason for hiding this comment

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

사실 1, 2, 3, 4 보다 이렇게 직접적으로 column 명을 명시해주는 것이 좋아보이긴 했는데 이렇게 바꿔주셨군요! 멋집니다

Copy link
Author

Choose a reason for hiding this comment

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

u 2

private final JdbcTemplate jdbcTemplate;

Expand All @@ -27,18 +26,16 @@ public UserDao(final JdbcTemplate jdbcTemplate) {

public void insert(final User user) {
final var sql = "insert into users (account, password, email) values (?, ?, ?)";

jdbcTemplate.update(sql, user.getAccount(), user.getPassword(), user.getEmail());
}

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

public List<User> findAll() {
final var sql = "select * from users";

return jdbcTemplate.query(sql, USER_ROW_MAPPER);
}

Expand Down
62 changes: 20 additions & 42 deletions app/src/main/java/com/techcourse/dao/UserHistoryDao.java
Original file line number Diff line number Diff line change
@@ -1,62 +1,40 @@
package com.techcourse.dao;

import com.techcourse.domain.UserHistory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

public class UserHistoryDao {

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

Choose a reason for hiding this comment

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

사용하지 않는 로그들도 다 지워주셨네요 역시 my gun ho zzang ..

Copy link
Author

Choose a reason for hiding this comment

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

ur jae yun zzang too

private static final RowMapper<UserHistory> USER_HISTORY_ROW_MAPPER = rs -> new UserHistory(
rs.getLong("id"),
rs.getLong("user_id"),
rs.getString("account"),
rs.getString("password"),
rs.getString("email"),
rs.getString("created_by"));

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) {}
}
jdbcTemplate.update(sql, userHistory.getUserId(), userHistory.getAccount(), userHistory.getPassword(),
userHistory.getEmail(), userHistory.getCreatedAt(), userHistory.getCreateBy());
}

public List<UserHistory> findByUserId(final Long userId) {
final var sql = "select * from user_history where user_id = ?";
return jdbcTemplate.query(sql, USER_HISTORY_ROW_MAPPER, userId);
}
}
40 changes: 40 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,40 @@
package com.techcourse.service;

import com.techcourse.dao.UserDao;
import com.techcourse.dao.UserHistoryDao;
import com.techcourse.domain.User;
import com.techcourse.domain.UserHistory;
import java.util.List;

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

public List<UserHistory> findLogsByUserId(final long id) {
return userHistoryDao.findByUserId(id);
}
}
Comment on lines +37 to +40

Choose a reason for hiding this comment

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

테스트를 위해 메서들르 추가해주셨군요! 좋습니다

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

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

public class TxUserService implements UserService {

private final UserService userService;

private final TransactionManager transactionManager;

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

@Override
public User findById(final long id) {
return transactionManager.executeWithResult(() -> userService.findById(id));
}

@Override
public void insert(final User user) {
transactionManager.execute(() -> userService.insert(user));
}

@Override
public void changePassword(final long id, final String newPassword, final String createBy) {
transactionManager.execute(() -> userService.changePassword(id, newPassword, createBy));
}
}
29 changes: 5 additions & 24 deletions app/src/main/java/com/techcourse/service/UserService.java
Original file line number Diff line number Diff line change
@@ -1,32 +1,13 @@
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);
}

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

48 changes: 38 additions & 10 deletions app/src/test/java/com/techcourse/service/UserServiceTest.java
Original file line number Diff line number Diff line change
@@ -1,28 +1,33 @@
package com.techcourse.service;

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

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 com.techcourse.support.jdbc.init.DatabasePopulatorUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
import javax.sql.DataSource;
import org.assertj.core.api.SoftAssertions;
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 org.springframework.transaction.support.TransactionManager;

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 DataSource dataSource;

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

DatabasePopulatorUtils.execute(DataSourceConfig.getInstance());
Expand All @@ -33,7 +38,7 @@ void setUp() {
@Test
void testChangePassword() {
final var userHistoryDao = new UserHistoryDao(jdbcTemplate);
final var userService = new UserService(userDao, userHistoryDao);
final var userService = new AppUserService(userDao, userHistoryDao);

final var newPassword = "qqqqq";
final var createBy = "gugu";
Expand All @@ -44,11 +49,34 @@ void testChangePassword() {
assertThat(actual.getPassword()).isEqualTo(newPassword);
}

@Test
void testChangePasswordWithUserHistory() {
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 List<UserHistory> logs = userService.findLogsByUserId(1L);

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

SoftAssertions.assertSoftly(
soft -> {
soft.assertThat(actual.getPassword()).isEqualTo(newPassword);
soft.assertThat(logs).hasSize(1);
}
);
}

@Test
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, new TransactionManager(dataSource));

final var newPassword = "newPassword";
final var createBy = "gugu";
Expand Down
15 changes: 14 additions & 1 deletion docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,18 @@
- [x] 예외처리 코드 작성
- [x] 쿼리 조회 결과가 2개 이상이거나 없을 경우 예외 처리
- [x] RuntimeException 대신 구체적 예외 처리

- [x] JDBC 탬플릿의 중복된 try catch문 제거

## 3단계
- [x] 매튜 리뷰 반영

Choose a reason for hiding this comment

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

my gun ho ... 의 readme 에 저의 닉네임이 들어가다니 이렇게 감동적일 수가 없습니다..

Copy link
Author

Choose a reason for hiding this comment

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

oh jae yun ... u r so kind~

- [x] JdbcTemplate 변수 네이밍 명확하게 수정
- [x] 사용하지 않는 log 제거

- [x] User에 비밀번호 변경 기능 구현
- [x] 변경 이력 저장
- [x] 트랜잭션 설정

## 4단계
- [x] Transaction synchronization 적용
- [x] 트랜잭션 서비스 추상화하기
- [x] 공통 코드 분리
Loading
Loading