1. 程式人生 > >Hibernate基於version的樂觀鎖

Hibernate基於version的樂觀鎖

    在Hibernate中,主要由Hibernate提供的版本控制功能來實現樂觀鎖定。Hibernate為樂觀鎖提供了兩種實現,分別基於version的實現和基於timestamp的實現。version元素利用一個遞增的整數來跟蹤資料表中記錄的版本;而timestamp元素則用時間來跟蹤資料庫表中記錄的版本。

accounts表結構


建立實體類
package com.dwx.models;
public class Accounts {
	private int id;
	private String username;
	private double money;
	private int version;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public double getMoney() {
		return money;
	}
	public void setMoney(double money) {
		this.money = money;
	}
	public int getVersion() {
		return version;
	}
	public void setVersion(int version) {
		this.version = version;
	}
}
配置對映
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<class name="com.dwx.models.Accounts" table="accounts">
		<id name="id">
			<generator class="native"></generator>
		</id>
		<version name="version"></version>
		<property name="username"></property>	
		<property name="money"></property>		
	</class>
</hibernate-mapping>
建立測試類
package com.dwx.models;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class Test {
	public static void main(String[] args) {
		Session session=null;
		Transaction tx=null;
		try{
			session=HibernateSessionFactory.getSession();
			tx=session.beginTransaction();
			Accounts a=(Accounts)session.load(Accounts.class, 1);
			a.setMoney(800);
			session.update(a);
			tx.commit();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			HibernateSessionFactory.closeSession();
		}
	}
}
執行結果: