#13 spring transaction - exception : rollback, commit

This commit is contained in:
haerong22
2022-07-18 03:23:55 +09:00
parent b79e4e155f
commit 602545de7a
2 changed files with 78 additions and 1 deletions

View File

@@ -1 +1,5 @@
logging.level.org.springframework.transaction.interceptor=TRACE
logging.level.org.springframework.transaction.interceptor=TRACE
logging.level.org.springframework.jdbc.datasource.DataSourceTransactionManager=DEBUG
#JPA log
logging.level.org.springframework.orm.jpa.JpaTransactionManager=DEBUG
logging.level.org.hibernate.resource.transaction=DEBUG

View File

@@ -0,0 +1,73 @@
package com.example.springtransaction.exception;
import lombok.extern.slf4j.Slf4j;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.annotation.Transactional;
@SpringBootTest
public class RollbackTest {
@Autowired
RollbackService rollbackService;
@Test
void runTimeException() {
Assertions.assertThatThrownBy(() -> rollbackService.runtimeException())
.isInstanceOf(RuntimeException.class);
}
@Test
void checkedException() {
Assertions.assertThatThrownBy(() -> rollbackService.checkedException())
.isInstanceOf(MyException.class);
}
@Test
void rollbackFor() {
Assertions.assertThatThrownBy(() -> rollbackService.rollbackFor())
.isInstanceOf(MyException.class);
}
@TestConfiguration
static class RollbackTestConfig {
@Bean
RollbackService rollbackService() {
return new RollbackService();
}
}
@Slf4j
static class RollbackService {
// 런타임 예외 발생 -> 롤백
@Transactional
public void runtimeException() {
log.info("call runtimeException");
throw new RuntimeException();
}
// 체크 예외 발생 -> 커밋
@Transactional
public void checkedException() throws MyException {
log.info("call checkedException");
throw new MyException();
}
// 체크 예외 rollbackFor 지정 -> 롤백
@Transactional(rollbackFor = MyException.class)
public void rollbackFor() throws MyException {
log.info("call rollbackFor");
throw new MyException();
}
}
static class MyException extends Exception {
}
}