Server/- mysql
Transaction, Commit , Rollback
즐겁게 하하하
2022. 3. 12. 10:09
728x90
Transaction : 더이상 나눌수 없는 작업의 단위
속성 : ACID
원자성(A) : 나눌수 없는 하나의 작업으로 다뤄져야
일관성(C) : 수행 전 후 가 일관된 상태가 되어야
고립성(I) : 각 트랜젝션은 독립적으로 수행되어야
영속성(D) : 성공한 트랜잭션의 결과는 유지되어야
자동커밋( Rollback 불가 ) , 수동커밋
Transaction isolation level
1. READ UNCOMMITED : 커밋되지 않은 데이터도 읽기 가능 - dirty read
2. READ COMMITED : 커밋된 데이터만 읽기 가능
3. REPEATABLE READ : 트랜잭션이 시작된 이후 변경은 무시됨
- default
- 커밋 해서 데이터 변경되도 현재 트랜젝션에 영향을 미치지 않음( 고립성 )
4. SERIALIZABLE : 한번에 하나의 트랜잭션만 독립적으로 수행
- tx1 > tx2 > tx3
- 직렬 처리 : 하나의 트랜젝션끝나기 전이면 다른 트랜젝션은 쓰기,삭제 불가능하며 대기상태로 만듬
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"file:src/main/webapp/WEB-INF/spring/**/root-context.xml"})
public class DBConnectionTest2Test {
@Autowired
DataSource ds;
private void deleteAll() throws Exception {
Connection conn = ds.getConnection();
String sql = "delete from user_info ";
PreparedStatement pstmt = conn.prepareStatement(sql); // SQL Injection공격, 성능향상
pstmt.executeUpdate(); // insert, delete, update
}
@Test
public void TransactionTest() throws Exception {
Connection conn = null;
try {
deleteAll();
conn = ds.getConnection();
conn.setAutoCommit(false); // 기본: Auto commit True
String sql = "insert into user_info values (?, ?, ?, ?,?,?, now()) ";
PreparedStatement pstmt = conn.prepareStatement(sql); // SQL Injection공격, 성능향상
pstmt.setString(1, "asdf");
pstmt.setString(2, "1234");
pstmt.setString(3, "abc");
pstmt.setString(4, "111@naver.com");
pstmt.setDate(5, new java.sql.Date(new Date().getTime()));
pstmt.setString(6, "fb");
int rowCnt = pstmt.executeUpdate(); // insert, delete, update
pstmt.setString(1, "ddd");
rowCnt = pstmt.executeUpdate();
conn.commit();
} catch (Exception e) {
conn.rollback();
e.printStackTrace();
}finally {
conn.close();
}
}
}
Propagation 속성
REQUIRED | Tx 진행중이면 참여, 없으면 새로운 Tx 시작( 디폴트 ) |
REQUIRES_NEW | 새로 Tx 시작 |
NESTED | Tx 진행중이면 Tx의 내부(sub Tx , save point ) Tx로 실행 |
MANDATORY | 반드시 진행중인 Tx 내에서만 실행가능, 아니면 예외발생 |
SUPPORTS | Tx 진행중이건 아니건 상관없이 실행 |
NOT_SUPPORTED | Tx 없이 처리, Tx 진행중이면 잠시 중단 |
NEVER | Tx 없이 처리, Tx 진행중이면 예외 발생 |
728x90