데이터를 저장할 때 단순히 파일에 저장해도 되는데 데이터베이스에 저장하는 이유는 무엇일까
여러가지 이유가 있지만 가장 대표적인 이유는 바로 데이터베이스는 트랜잭션이라는 개념을 지원하기 때문이다
트랜잭션은 거래라는 뜻으로 , 데이터베이스에서 트랜잭션은 하나의 거래를 안전하게 처리하도록 보장해 주는 것을 뜻한다. 그런데 하나의 거래를 안전하게 처리하려면 생각보다 고려해야할 점이 많다.
5,000원 계좌이체
계좌이체라는 거래는 2개의 작업이 합쳐져서 하나의 작업처럼 동작해야한다. 만약 1번은 성공했는데 2번에서 문제가 발생하면 계좌이체는 실패하고 A의 잔고만 5,000원 감소하는 심각한 문제가 발생한다.
데이터베이스가 제공하는 트랜잭션을 사용하면 1,2 둘다 성공해야지 정상적으로 로직이 실행되고 둘중 하나라도 실패하면 거래 이전의 상태로 되돌아간다.
모든 작업이 성공해서 데이터베이스에 정상 반영하는 것을 커밋(commit)이라 하고 작업 중 하나라도 실패해서 거래 이전으로 되돌리는 것을 롤백(rollback)이라 한다.
트랜잭션 ACID
트랜잭션은 원자성,일관성, 지속성을 보장한다. 문제는 격리성인데 트랜잭션간에 격리성을 완벽히 보장하려면 트랜잭션을 거의 순서대로 실행해야한다. 이렇게 하면 동시 처리 성능이 매우 나빠진다. 이런 문제로 인해 ANSI 표준은 트랜 잭션의 격리 수준을 4단계로 나누어 정의했다.
데이터베이스 연결 구조
사용자는 웹 어플리케이션 서버(Was)나 DB 접근 툴 같은 클라이언트를 사용해서 데이터베이스 서버에 접근할 수 있다. 클라이언트는 데이터베이스 서버에 연결을 요청하고 커넥션을 맺게된다. 이때 데이터베이스 서버는 내부에 세션이라는 것을 만든다. 앞으로 해당 커넥션을 통한 모든 요청은 이 세션을 통해서 실행된다.
개발자가 클라이언트를 통해 SQl을 전달하면 현재 커넥션에 연결된 세션이 SQl을 실행한다
세션은 트랜잭션을 시작하고 commit
,rollback
을 통해 트랜잭션을 종료한다
사용자가 커넥션을 닫거나 DBA가 세션을 강제로 종료하면 세션은 종료된다
트랜잭션 사용법
commit
을 호출하고 결과를 반영하고 싶지 않다면 롤백 명령어인 rollback
을 호출하면 된다커밋하지않은 데이터 조회 가능 시
자동 & 수동 커밋
자동 커밋으로 설정하면 각각의 쿼리 실행 직후에 자동으로 커밋을 호출한다. 따라서 커밋이나 롤백을 직접 호출하지 않아도 되는 편리함이 있다. 하지만 쿼리를 하나하나 실행할 때마다 자동으로 커밋이 되어버리기 때문에 트랜잭션 기능을 제대로 수행할 수 없다.
set autocommit true; //자동 커밋 모드 설정
insert into member(member_id, money) values ('data1',10000); //자동 커밋
insert into member(member_id, money) values ('data2',10000); //자동 커밋
commit
,rollback
을 직접 호출하면서 트랜잭션 기능을 제대로 수행하려면 자동 커밋을 끄고 수동 커밋을 사용해야한다set autocommit false; //수동 커밋 모드 설정
insert into member(member_id, money) values ('data3',10000);
insert into member(member_id, money) values ('data4',10000);
commit; //수동 커밋
commit
,rollback
을 호출해야 함서로 다른 세션에서 데이터를 수정하려고 하면 데이터가 엉킬 가능성이 있다. 이런 문제를 방지하기 위해
세션이 트랜잭션을 시작하고 데이터를 수정하는 동안에는 커밋이나 롤백 전까지 다른 세션에서 해당 데이터를 수정할 수 없게 막아야한다.
락 예제
memberA
의 금액을 500원으로 변경하고 싶지만 세션2는 memberA
의 금액을 1000원으로 변경하고자 한다memberA
의 데이터를 변경을 시도했지만 락이 없으므로 락이 돌아올 때까지 기다린다 SET LOCK_TIMEOUT 60000;
set autocommit false;
update member set money=1000 where member_id = 'memberA';
일반적인 조회는 락을 사용하지 않는다
데이터 변경이 아닌 일반적인 조회는 락이 필요하지 않아 다른 세션이 락을 가지고 있는 상태라도 상관이 없다
데이터를 조회할 때도 락을 획득하고 싶을 때는 select for update
구문을 사용하면 된다.
이 경우 세션1이 조회 시점에 락을 가져가버리기 때문에 다른 세션에서 해당 데이터를 변경 할 수 없다.
조회 시점에 락이 필요한 경우
memberA
의 금액을 조회한 다음에 이 금액 정보로 애플리케이션에서 어떤 계산을 수행한다. 그런데 이 계산이 돈과 관련된 매우 중요한 계산이어서 계산을 완료할 때 까지 memberA
의 금 액을 다른곳에서 변경하면 안된다. 이럴 때 조회 시점에 락을 획득하면 된다비즈니스 로직과 트랜잭션
MemberRepositoryV2
@Slf4j
public class MemberRepositoryV2 {
private final DataSource dataSource;
public MemberRepositoryV2(DataSource dataSource) {
this.dataSource = dataSource;
}
public Member save(Member member) throws SQLException {
String sql = "insert into member(member_id, money) values(?, ?)";
Connection con = null;
PreparedStatement pstmt = null;
try {
con = getConnection();
pstmt = con.prepareStatement(sql);
pstmt.setString(1, member.getMemberId());
pstmt.setInt(2, member.getMoney());
pstmt.executeUpdate();
return member;
} catch (SQLException e) {
log.error("db error", e);
throw e;
} finally {
close(con, pstmt, null);
}
}
public Member findById(String memberId) throws SQLException {
String sql = "select * from member where member_id = ?";
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
con = getConnection();
pstmt = con.prepareStatement(sql);
pstmt.setString(1, memberId);
rs = pstmt.executeQuery();
if (rs.next()) {
Member member = new Member();
member.setMemberId(rs.getString("member_id"));
member.setMoney(rs.getInt("money"));
return member;
} else {
throw new NoSuchElementException("member not found memberId="
+ memberId);
}
} catch (SQLException e) {
log.error("db error", e);
throw e;
} finally {
close(con, pstmt, rs);
}
}
public Member findById(Connection con, String memberId) throws
SQLException {
String sql = "select * from member where member_id = ?";
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
pstmt = con.prepareStatement(sql);
pstmt.setString(1, memberId);
rs = pstmt.executeQuery();
if (rs.next()) {
Member member = new Member();
member.setMemberId(rs.getString("member_id"));
member.setMoney(rs.getInt("money"));
return member;
} else {
throw new NoSuchElementException("member not found memberId="+ memberId);
}
} catch (SQLException e) {
log.error("db error", e);
throw e;
} finally {
//connection은 여기서 닫지 않는다.
JdbcUtils.closeResultSet(rs);
JdbcUtils.closeStatement(pstmt);
}
}
public void update(String memberId, int money) throws SQLException {
String sql = "update member set money=? where member_id=?";
Connection con = null;
PreparedStatement pstmt = null;
try {
con = getConnection();
pstmt = con.prepareStatement(sql);
pstmt.setInt(1, money);
pstmt.setString(2, memberId);
pstmt.executeUpdate();
} catch (SQLException e) {
log.error("db error", e);
throw e;
} finally {
close(con, pstmt, null);
}
}
public void update(Connection con, String memberId, int money) throws
SQLException {
String sql = "update member set money=? where member_id=?";
PreparedStatement pstmt = null;
try {
pstmt = con.prepareStatement(sql);
pstmt.setInt(1, money);
pstmt.setString(2, memberId);
pstmt.executeUpdate();
} catch (SQLException e) {
log.error("db error", e);
throw e;
} finally {
//connection은 여기서 닫지 않는다.
JdbcUtils.closeStatement(pstmt);
}
}
public void delete(String memberId) throws SQLException {
String sql = "delete from member where member_id=?";
Connection con = null;
PreparedStatement pstmt = null;
try {
con = getConnection();
pstmt = con.prepareStatement(sql);
pstmt.setString(1, memberId);
pstmt.executeUpdate();
} catch (SQLException e) {
log.error("db error", e);
throw e;
} finally {
close(con, pstmt, null);
}
}
private void close(Connection con, Statement stmt, ResultSet rs) {
JdbcUtils.closeResultSet(rs);
JdbcUtils.closeStatement(stmt);
JdbcUtils.closeConnection(con);
}
private Connection getConnection() throws SQLException {
Connection con = dataSource.getConnection();
log.info("get connection={} class={}", con, con.getClass());
return con;
}
}
findById(Connection con, String memberId)
update(Connection con, String memberId, int money)
con = getConnection()
코드가 있으면 안된다.MemberService2
@Slf4j
@RequiredArgsConstructor
public class MemberServiceV2 {
private final DataSource dataSource;
private final MemberRepositoryV2 memberRepository;
public void accountTransfer(String fromId, String toId, int money) throws
SQLException {
Connection con = dataSource.getConnection();
try {
con.setAutoCommit(false); //트랜잭션 시작 //비즈니스 로직
bizLogic(con, fromId, toId, money);
con.commit(); //성공시 커밋
} catch (Exception e) {
con.rollback(); //실패시 롤백
throw new IllegalStateException(e);
} finally {
release(con);
}
}
private void bizLogic(Connection con, String fromId, String toId, int
money) throws SQLException {
Member fromMember = memberRepository.findById(con, fromId);
Member toMember = memberRepository.findById(con, toId);
memberRepository.update(con, fromId, fromMember.getMoney() - money);
validation(toMember);
memberRepository.update(con, toId, toMember.getMoney() + money);
}
private void validation(Member toMember) {
if (toMember.getMemberId().equals("ex")) {
throw new IllegalStateException("이체중 예외 발생"); }
}
private void release(Connection con) {
if (con != null) {
try {
con.setAutoCommit(true); //커넥션 풀 고려
con.close();
} catch (Exception e) {
log.info("error", e);
}
}
}
}
출처: https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-db-1