package hello.jbdc.repository
import hello.jbdc.Log
import hello.jbdc.domain.Member
import org.springframework.jdbc.datasource.DataSourceUtils
import org.springframework.jdbc.support.JdbcUtils
import java.sql.*
import javax.sql.DataSource
import kotlin.jvm.Throws
/*
* 트랜잭션 매니저
* DataSourceUtils.getConnection()
* DataSourceUtils.releaseConnection()*/
class MemberRepositoryV3(
private val dataSource: DataSource,
):Log {
fun save(member: Member): Member{
val sql: String = "insert into member(member_id, money) values (?, ?)"
lateinit var con: Connection
lateinit var pstmt: PreparedStatement
try{
con = getConnection()
pstmt = con.prepareStatement(sql)
pstmt.setString(1, member.memberId)
pstmt.setInt(2, member.money)
pstmt.executeUpdate()
return member
} catch(e: SQLException){
logger.error("db error", e)
e.printStackTrace()
throw e
} finally {
close(con, pstmt, null);
}
}
@Throws(SQLException::class)
fun findById(memberId: String): Member{
val sql = "select * from member where member_id = ?"
lateinit var con: Connection
lateinit var pstmt: PreparedStatement
lateinit var rs: ResultSet
try{
con = getConnection()
pstmt = con.prepareStatement(sql)
pstmt.setString(1, memberId)
rs = pstmt.executeQuery()
if (rs.next()){
val member = Member(
memberId = rs.getString("member_id"),
money = rs.getInt("money")
)
return member
}else{
throw NoSuchElementException("member not found memberId=" + memberId)
}
} catch (e: SQLException){
logger.error("db error", e)
throw e
} finally {
close(con, pstmt, null)
}
}
@Throws(SQLException::class)
fun update(memberId: String, money: Int){
val sql = "update member set money=? where member_id=?"
lateinit var con: Connection
lateinit var pstmt: PreparedStatement
try {
con = getConnection();
pstmt = con.prepareStatement(sql);
pstmt.setInt(1, money);
pstmt.setString(2, memberId);
val resultSize = pstmt.executeUpdate()
logger.info("resultSize={}", resultSize)
} catch (e: SQLException){
logger.error("db error", e)
throw e
} finally {
close(con, pstmt, null)
}
}
@Throws(SQLException::class)
fun delete(memberId: String){
val sql = "delete from member where member_id=?"
lateinit var con: Connection
lateinit var pstmt: PreparedStatement
try {
con = getConnection();
pstmt = con.prepareStatement(sql);
pstmt.setString(1, memberId);
pstmt.executeUpdate()
} catch (e: SQLException){
logger.error("db error", e)
throw e
} finally {
close(con, pstmt, null);
}
}
private fun getConnection(): Connection {
// 주의! 트랜잭션 동기화를 사용하려면 DataSourceUtils를 사용해야 한다.
val con = DataSourceUtils.getConnection(dataSource)
logger.info("get connection={}, class={}", con, con.javaClass)
return con
}
private fun close(con: Connection?, stmt: Statement?, rs: ResultSet?) {
JdbcUtils.closeResultSet(rs);
JdbcUtils.closeStatement(stmt);
// 주의! 트랜잭션 동기화를 사용하려면 DataSourceUtil을 사용해야 합니다.
DataSourceUtils.releaseConnection(con, dataSource)
}
}
package hello.jbdc.service
import hello.jbdc.Log
import hello.jbdc.domain.Member
import hello.jbdc.repository.MemberRepositoryV3
import org.springframework.transaction.PlatformTransactionManager
import org.springframework.transaction.TransactionStatus
import org.springframework.transaction.support.DefaultTransactionDefinition
import java.sql.Connection
import java.sql.SQLException
import kotlin.jvm.Throws
/*
트랜잭션 - 트랜잭션 매니저
*/
class MemberServiceV3_1(
private val transactionManager: PlatformTransactionManager,
private val memberRepository: MemberRepositoryV3,
) :Log {
@Throws(SQLException::class)
fun accountTransfer(fromId: String, toId: String, money: Int){
// 트랜잭션 시작
val status: TransactionStatus = transactionManager.getTransaction(DefaultTransactionDefinition())
try {
bizLogic(fromId, toId, money)
transactionManager.commit(status)
}catch (e: Exception){
transactionManager.rollback(status)
throw IllegalStateException(e)
}
}
@Throws(SQLException::class)
private fun bizLogic(fromId: String, toId: String, money: Int){
val fromMember = memberRepository.findById(fromId)
val toMember = memberRepository.findById(toId)
memberRepository.update(fromId, fromMember.money - money)
validation(toMember)
memberRepository.update(toId, fromMember.money + money)
}
private fun validation(toMember: Member){
if (toMember.memberId.equals("ex")){
throw IllegalStateException("이체 중 예외 발생")
}
}
}
package hello.jbdc.service
import hello.jbdc.connection.ConnectionConst
import hello.jbdc.domain.Member
import hello.jbdc.repository.MemberRepositoryV3
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.springframework.jdbc.datasource.DataSourceTransactionManager
import org.springframework.jdbc.datasource.DriverManagerDataSource
import org.springframework.transaction.PlatformTransactionManager
import java.sql.SQLException
internal class MemberServiceV3_1Test{
val MEMBER_A = "memberA"
val MEMBER_B = "memberB"
val MEMBER_EX = "ex"
lateinit var memberRepository: MemberRepositoryV3
lateinit var memberService: MemberServiceV3_1
@BeforeEach
fun before(){
val dataSource = DriverManagerDataSource(ConnectionConst.URL,
ConnectionConst.USERNAME, ConnectionConst.PASSWORD)
val transactionManager: PlatformTransactionManager = DataSourceTransactionManager(dataSource)
memberRepository = MemberRepositoryV3(dataSource)
memberService = MemberServiceV3_1(transactionManager, memberRepository)
}
@AfterEach
@Throws(SQLException::class)
fun after(){
memberRepository.delete(MEMBER_A);
memberRepository.delete(MEMBER_B);
memberRepository.delete(MEMBER_EX);
}
@Test
@DisplayName("정상 이체")
@Throws(SQLException::class)
fun accountTransfer() {
//given
val memberA = Member(MEMBER_A, 10000)
val memberB = Member(MEMBER_B, 10000)
memberRepository.save(memberA)
memberRepository.save(memberB)
//when
memberService.accountTransfer(memberA.memberId,
memberB.memberId, 2000)
// //then
val findMemberA: Member = memberRepository.findById(memberA.memberId)
val findMemberB: Member = memberRepository.findById(memberB.memberId)
assertThat(findMemberA.money).isEqualTo(8000)
assertThat(findMemberB.money).isEqualTo(12000)
}
@Test
@DisplayName("이체 중 예외 발생")
fun accountTransferEx(){
//given
val memberA = Member(MEMBER_A, 10000)
val memberEx = Member(MEMBER_EX, 10000)
memberRepository.save(memberA)
memberRepository.save(memberEx)
// when
assertThatThrownBy {
memberService.accountTransfer(memberA.memberId, memberEx.memberId,
2000)
}
.isInstanceOf(IllegalStateException::class.java)
// then
val findMemberA = memberRepository.findById(memberA.memberId)
val findMemberEx = memberRepository.findById(memberEx.memberId)
assertThat(findMemberA.money).isEqualTo(10000)
assertThat(findMemberEx.money).isEqualTo(10000)
}
}
1. 서비스 계층에서 transactionManager.getTransaction()을 호출해서 트랜잭션을 시작한다.
2. 트랜잭션을 시작하려면 먼저 데이터베이스 커넥션이 필요하다. 트랜잭션 매니저는 내부에서 데이터 소스를 사용해서 커넥션을 생성한다.
3. 커넥션을 수동 커밋 모드로 변경해서 실제 데이터베이스 트랜잭션을 시작한다.
4. 커넥션을 트랜잭션 동기화 매니저에 보관한다.
5. 랜잭션 동기화 매니저는 쓰레드 로컬에 커넥션을 보관한다. 따라서 멀티 쓰레드 환경에 안전하게 커넥션을 보관할 수 있다.
6. 서비스는 비즈니스 로직을 실행하면서 리포지토리의 메서드들을 호출한다. 이 때 커넥션을 파라미터로 전달하지 않는다.
7. 리포지토리 메서드들은 트랜잭션이 시작된 커넥션이 필요하다. 리포지토리는 DataSourceUtils.getConnection() 을 사용해서 트랜잭션 동기화 매니저에 보관된 커넥션을 꺼내서 사용한다. 이 과정을 통해서 자연스럽게 같은 커넥션을 사용하고, 트랜잭션도 유지된다.
8. 획득한 커넥션을 사용해서 SQL을 데이터베이스에 전달해서 실행한다.
9. 비즈니스 로직이 끝나고 트랜잭션을 종료한다. 트랜잭션은 커밋하거나 롤백하면 종료된다.
10. 트랜잭션을 종료하려면 동기화된 커넥션이 필요하다. 트랜잭션 동기화 매니저를 통해 동기화된 커넥션을 획득한다.
11. 획득한 커넥션을 통해 데이터베이스에 트랜잭션을 커밋하거나 롤백한다.
12. 전체 리소스를 정리한다.