[Spring] 10. Transaction, Commit, Rollback

Hyeongmin Jung·2023년 8월 3일
0

MySQL

목록 보기
2/2

Transaction

: 더 이상 나눌 수 없는 작업의 단위
ex) 계좌이체의 경우 출금+입금➪Tx
둘다 성공해야만 성공, 둘중 하나만 실패해도 취소(Rollback)

📌 Transaction 속성 - ACID

✅ 원자성(Atomicity): 나눌 수 없는 하나의 작업으로 다뤄져야 함
✅ 일관성(Consistency): Tx 수행 전과 후가 일관된 상태를 유지해야 함
✅ 고립성(Isolation): 각 Tx는 독립적으로 수행되어야 함
isolation level에 따라 어느정도 영향을 허용
✅ 영속성(Durability): 성공한 Tx의 결과는 유지되어야 함

Commit, Rollback

☑️ Commit: 작업 내용을 DB에 영구적으로 저장
☑️ Rollback: 최근 변경사항을 취소하고 최근(마지막) 커밋으로 복귀, 커밋후 rollback 불가

🎞️ 자동커밋과 수동커밋

✅ 자동 커밋(Auto Commit 기본): 명령 실행 후, 자동으로 커밋 수행(rollback불가)
✅ 수동 커밋(SET autocommit=0;): 명령 실행 후, 명시적으로 commit 또는 rollback 입력
ex) 2개 이상의 명령어로 이루어진 transaction의 경우 수동커밋 사용

🎄Tx의 isolation level

: 각 Tx를 고립 시키는 정도
➊ READ UNCOMMITED: 커밋되지 않는 데이터도 읽기 가능, dirty read
➋ READ COMMITED: 커밋된 데이터만 읽기 가능, phantom read
➌ REPEATABLE READ: Tx이 시작된 이후 변경은 무시됨 | default
➍ SERIALIZABLE: 직렬화, 한 번에 하나의 Tx만 완전히 독립적으로 수행, 성능은 떨어지지만 data 품질은 높음 | 고립도↑

실습

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"file:src/main/webapp/WEB-INF/spring/**/root-context.xml"}) 
public class DBConnectionTest2Test {
    @Autowired 
    DataSource ds;
    
    @Test
    public void transactionTest() throws Exception {
        Connection conn = null;
        try {
            deleteAll();
            conn = ds.getConnection();

            // true로 설정하면 여러개의 transaction이 하나로 묶이지 않고 각각 실행 후 자동 commit됨
            conn.setAutoCommit(false); // default | conn.setAutoCommit(true);

            String sql = "insert into user_info values (?, ?, ?, ?, ?, ?, now())";

            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, "asdf");
            pstmt.setString(2, "1234");
            pstmt.setString(3, "abc");
            pstmt.setString(4, "aaa@aaa.com");
            pstmt.setDate(5, new java.sql.Date(new Date().getTime()));
            pstmt.setString(6, "fb");

            int rowCnt = pstmt.executeUpdate();

            pstmt.setString(1, "asdf2");
            rowCnt = pstmt.executeUpdate();

            conn.commit();

        } catch (Exception e) {
            conn.rollback();
            e.printStackTrace();
        } finally {}
    }
}

0개의 댓글