Docs Menu
Docs Home
/ / /
Kotlin Sync 드라이버
/

트랜잭션

이 페이지의 내용

  • 개요
  • 샘플 데이터
  • 방법
  • 예제
  • 추가 정보
  • API 문서

이 가이드 에서는 코틀린 동기 (Kotlin Sync) 운전자 를 사용하여 트랜잭션 을 수행하는 방법을 학습 수 있습니다. 트랜잭션을 사용하면 트랜잭션 이 커밋될 때까지 데이터를 변경하지 않는 일련의 작업을 실행 수 있습니다. 트랜잭션 에서 오류가 반환되는 경우 운전자 는 트랜잭션 을 취소하고 데이터 변경 사항이 표시되기 전에 모든 데이터 변경 사항을 삭제합니다.

MongoDB에서 트랜잭션은 논리적 세션 내에서 실행됩니다. 세션은 순차적으로 실행하려는 관련 읽기 또는 쓰기 작업의 그룹입니다. 세션을 사용하면 작업 그룹에 인과적 일관성 을 부여하고 원자성, 일관성, 격리 및 내구성에 대한 기대치를 충족하는 트랜잭션인 ACID 호환 트랜잭션 에서 작업을 실행할 수 있습니다. MongoDB는 작업에 예기치 않은 오류가 발생하더라도 트랜잭션 작업과 관련된 데이터의 일관성을 보장합니다.

코틀린 동기 (Kotlin Sync) 운전자 를 사용하는 경우 MongoClient 인스턴스 에서 ClientSession 유형으로 새 세션을 만들 수 있습니다. 매번 새 클라이언트 를 생성하는 대신 여러 세션 및 트랜잭션에 MongoClient 를 재사용하는 것이 좋습니다.

경고

ClientSession을(를) 생성한 MongoClient (또는 MongoDatabase 또는 MongoCollection)에만 ClientSession을(를) 사용합니다. 다른 MongoClient와(과) 함께 ClientSession을(를) 사용하면 작업 오류가 발생합니다.

이 가이드의 예제에서는 Atlas 샘플 데이터 세트sample_restaurants.restaurants 컬렉션을 사용합니다. 무료 MongoDB Atlas 클러스터를 생성하고 샘플 데이터 세트를 로드하는 방법을 알아보려면 Atlas 시작하기 가이드를 참조하세요.

이 컬렉션의 문서는 다음 Kotlin 데이터 클래스에 따라 모델링됩니다.

data class Restaurant(val name: String, val cuisine: String)

MongoClient 인스턴스에서 startSession() 메서드를 사용하여 ClientSession 를 만듭니다. 그런 다음 ClientSession 에서 제공하는 메서드를 사용하여 세션 상태를 수정할 수 있습니다. 다음 표에서는 트랜잭션을 관리하는 데 사용할 수 있는 방법에 대해 설명합니다.

메서드
설명
startTransaction()
Starts a new transaction, configured with the given options, on this session. Returns an error if there is already a transaction in progress for the session. To learn more about this method, see the startTransaction() page in the Server manual.

Parameter: TransactionOptions
abortTransaction()
Ends the active transaction for this session. Returns an error if there is no active transaction for the session or the transaction has been committed or ended. To learn more about this method, see the abortTransaction() page in the Server manual.

commitTransaction()
Commits the active transaction for this session. Returns an error if there is no active transaction for the session or if the transaction was ended. To learn more about this method, see the commitTransaction() page in the Server manual.
withTransaction()
Starts a transaction on this session and runs the given function within a transaction.

Parameters: transaction body function, TransactionOptions

다음 예시 에서는 다음 단계를 통해 한 번의 트랜잭션 으로 세션을 만들고, 트랜잭션 을 만들고, 컬렉션 에 문서를 삽입하는 방법을 보여 줍니다.

  1. startSession() 메서드를 사용하여 클라이언트에서 세션을 만듭니다.

  2. insertRestaurantsInTransaction() 메서드를 정의하여 restaurants 컬렉션 에 여러 문서를 삽입합니다.

  3. withTransaction() 메서드를 사용하여 트랜잭션 을 시작합니다. withTransaction() 메서드는 삽입 작업을 실행하고 트랜잭션 을 커밋합니다. 작업 중 오류가 발생하면 withTransaction() 트랜잭션 을 취소합니다.

  4. MongoClient.close() 메서드를 사용하여 서버와의 연결을 닫습니다.

// Creates a new MongoClient to manage your connection
val client = MongoClient.create("<connection string>")
// Gets the database and collection
val database = client.getDatabase("sample_restaurants")
val collection = database.getCollection<Restaurant>("restaurants")
// Inserts restaurants into the collection
fun insertRestaurantsInTransaction(session: ClientSession) {
// Inserts restaurants within the transaction
collection.insertOne(
session,
Restaurant("Kotlin Sync Pizza", "Pizza")
)
collection.insertOne(
session,
Restaurant("Kotlin Sync Burger", "Burger")
)
}
// Starts a client session
client.startSession().use { session ->
try {
// Sets transaction options
val txnOptions = TransactionOptions.builder()
.readConcern(ReadConcern.LOCAL)
.writeConcern(WriteConcern.MAJORITY)
.build()
// Uses the withTransaction method to start a transaction and run the given function
session.withTransaction({
insertRestaurantsInTransaction(session)
println("Transaction succeeded")
}, txnOptions)
} catch (e: Exception) {
println("Transaction failed: ${e.message}")
}
}
// Closes the MongoClient
client.close()

트랜잭션에 대한 더 많은 제어가 필요한 경우 startTransaction() 메서드를 사용할 수 있습니다. 이 메서드를 이전 섹션에서 설명한 commitTransaction()abortTransaction() 메서드와 함께 사용하여 트랜잭션 수명 주기를 수동으로 관리할 수 있습니다.

이 가이드에 언급된 개념에 대해 자세히 알아보려면 서버 매뉴얼의 다음 페이지를 참조하세요.

ACID 규정 준수에 대해 자세히 알아보려면 데이터베이스 관리 시스템의 ACID 속성이란 무엇인가요?를 참조하세요. MongoDB 웹사이트의 문서입니다.

이 가이드에서 설명하는 유형 또는 메서드에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.

돌아가기

대량 쓰기 작업