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

5.2 트랜잭션 서비스 추상화 #2

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open

5.2 트랜잭션 서비스 추상화 #2

wants to merge 1 commit into from

Conversation

twoosky
Copy link
Collaborator

@twoosky twoosky commented Nov 10, 2022

트랜잭션을 부셔보자

assertThat(userWithoutLevelRead.getLevel(), is(Level.BASIC));
}

static class TestUserService extends UserService {
Copy link
Collaborator Author

@twoosky twoosky Nov 10, 2022

Choose a reason for hiding this comment

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

  • 모든 사용자 레벨을 업그레이드 하는 도중 예외가 발생해서 작업이 중단되는 경우 변경된 작업도 모두 취소시킨다.
  • 그럼, 현재 코드에서 중간에 예외가 발생하면 이미 변경된 사용자의 레벨은 작업 이전 상태로 돌아갈까?
    아니면 바뀐 채로 남아 있을까?

TestUserService 는 강제로 예외를 발생시키기 위한 테스트용 클래스를 정의한 것이다.

  • UserService를 상속해서 테스트에 필요한 기능을 추가하도록 일부 메소드를 오버라이딩한다.
  • 테스트에서만 사용할 클래스라면 번거롭게 파일을 따로 만들지 말고 테스트 클래스 내부에 static 클래스로 만드는 것이 간편하다.

if (user.getId().equals(this.id)) throw new TestUserServiceException();
super.upgradeLevel(user);
}
}
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

UserService의 upgradeLevel을 오버라이딩 했다.

  • 미리 지정된 id를 가진 사용자가 발견되면 강제로 예외를 던진다.
  • 테스트 목적의 예외인 TestUserServiceException 도 테스트 클래스 내 static 멤버 클래스로 만든다.

@Test
public void upgradeAllOrNothing() {
UserService testUserService = new TestUserService(users.get(3).getId());
testUserService.setUserDao(this.userDao);
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

user id가 3인 사용자가 발견되면 강제로 예외를 던진다.

catch (TestUserServiceException ignored) {
}

checkLevel(users.get(1), false);
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

원하는 결과: 예외가 발생했으므로, SILVER로 업그레이된 user1의 레벨이 BASIC으로 돌아와야된다.
실제 결과: 예외 발생했음에도 SILVER로 레벨이 유지된다.

  • 원인
    • upgradeLevels() 메소드가 하나의 트랜잭션 안에서 동작하지 않았기 때문이다.
    • 레벨 업그레이드 작업은 전체가 성공하거나 전체가 실패해야 한다.
    • 중간에 예외 발생 시 초기 상태로 되돌려놔야 한다.
    • 따라서 upgradeLevels() 메소드에 트랜잭션을 적용해야 한다.

트랜잭션이란 더 이상 나눌 수 없는 단위의 작업을 말한다. (원자성)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant