Java Persistence Lock

使用Java Persistence中的@Version來執行Optimistic Locking.

1. 在資料庫中加入一個欄位for version checking, 在Oracle 中有個rowid, 只要資料有修改, 這個rowid就會跟著改變, 除了SQL Base外, 我所知的在其它的資料庫沒有這個機制. 但Oracle的rowid不能修改.

ALTER TABLE  my_table  ADD version_id bigint default 0  ;

update  my_table  set version_id=0

2.在Entity Class內加入

import javax.persistence.Version;

….

….

@Version
@Column(name = “version_id")
private Long version;

public Long getVersion() {
return version;
}

public void setVersion(Long version) {
this.version = version;
}

如此一來, JPA從資料庫讀入時, 會把version_id讀進來, 在update時, 除了primary key外, 還會去判斷這個欄位是否和原來讀入的一樣, 如果不一樣, 就會發出exception, 不讓JPA寫到資料庫.

如果成功寫入的話, 則會自動的把這個欄位的值加一.

http://en.wikibooks.org/wiki/Java_Persistence/Locking#Common_Locking_Mistakes.2C_Questions_and_Problems

https://java.sun.com/javaee/5/docs/api/javax/persistence/Version.html

http://en.wikibooks.org/wiki/Java_Persistence

EJB 3.0 Persistence – using the @Version annotation for Optimistic Locking – in the GlassFish Reference Implementation by Lucas Jellema

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *

What is 7 + 2 ?
Please leave these two fields as-is:
IMPORTANT! To be able to proceed, you need to solve the following simple math (so we know that you are a human) :-)