//pojos
public class OptimisticLock implements Serializable {
private int id;
private String name;
private double money;
private int ver;
public OptimisticLock() {
super();
// TODO Auto-generated constructor stub
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public OptimisticLock(String name, double money) {
super();
this.name = name;
this.money = money;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
public int getVer() {
return ver;
}
public void setVer(int ver) {
this.ver = ver;
}
@Override
public String toString() {
return "id=" + getId() + ", name="+ getName() + ", money="+ getMoney() + ", version" + getVer();
}
}
//这是OptimisticLock.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping
package="cn.itcast.pojos">
<class name="OptimisticLock" table="optimisticLock" optimistic-lock="version">
<id name="id" column="id">
<generator class="native"></generator>
</id>
<version name="ver" column="version"></version>
<property name="name" column="name"></property>
<property name="money" column="money"></property>
</class>
</hibernate-mapping>
//这是测试类
import org.hibernate.Session;
import org.hibernate.Transaction;
import cn.itcast.pojos.OptimisticLock;
import cn.itcast.util.HibernateSessionFactory;
public class Test {
public static void main(String[] args) {
Session session1 = HibernateSessionFactory.getSession();
Session session2 = HibernateSessionFactory.getSession();
Transaction transaction1 = session1.beginTransaction();
Transaction transaction2 = session2.beginTransaction();
OptimisticLock lock1 = (OptimisticLock) session1.get(OptimisticLock.class, 5);
OptimisticLock lock2 = (OptimisticLock) session2.get(OptimisticLock.class, 5);
lock1.setMoney(1000);
transaction1.commit();
lock2.setMoney(2000);
transaction2.commit();
session1.close();
session2.close();
}
}