そごうソフトウェア研究所

SOA、開発プロセス、ITアーキテクチャなどについて書いています。Twitterやってます@rsogo

3.4.1 Optimistic Locking

続いて、3.4.1に行きます。要はトランザクションが入れ子になって、データベースのデータに不整合が発生するとOptimisticLockExceptionが起きてトランザクションロールバックされますよ。もし、ロック使いたくないなら、アプリ側でなんとかしてね、ということでしょうか。

Optimistic locking is a technique that is used to insure that updates to the database data corresponding to the state of an entity are made only when no intervening transaction has updated that data for the entity state since the entity state was read. This insures that updates or deletes to that data are consistent with the current state of the database and that intervening updates are not lost. Transactions that would cause this constraint to be violated result in an OptimisticLockException being thrown and transaction rollback.

楽観的ロックは、エンティティを読み込んだ状態からデータベースのデータを更新するまでに、他のトランザクションが途中で状態を変えていないということを保障するための一つのテクニックである。これにより、データベースの現在の状態と一致するデータを更新したり、削除したりすること及び間に挟まったトランザクションが、ロストされてしまわないことを保障します。この制約を犯すトランザクションはOptimisticLockExceptionを引き起こし、トランザクションロールバックします。

Portable applications that wish to enable optimistic locking for entities must specify Version attributes for those entities―i.e., persistent properties or fields annotated with the Version annotation or specified in the XML descriptor as version attributes.

移植性の高いアプリケーションにするには、楽観的ロックを使用するときには対象となるエンティティにVersion属性を指定する必要がある。Version属性は以下の3つの指定方法がある。

Applications are strongly encouraged to enable optimistic locking for all entities that may be concurrently accessed or merged from a disconnected state.

アプリケーションは接続されていない状態(どういうことだろう?)からの並行してアクセスされたり、マージされる全てのエンティティに対して楽観的ロックを可能にすることを強く促される。

Failure to use optimistic locking may lead to inconsistent entity state, lost updates and other state irregularities. If optimistic locking is not defined as part of the entity state, the application must bear the burden of maintaining data consistency.

楽観的ロックを使用しない場合は、一貫性のないエンティティの状態、アップデートのロスト、その他いろいろな不整合を引き起こす可能性がある。その時は、アプリケーション側でデータの一貫性を維持ね。