1. Create a new version field in the datasheet, either int or bigint
2. Add a version field to the JavaBean
Package Net.spring.model;
Import Javax.persistence.Column;
Import javax.persistence.Entity;
Import Javax.persistence.Id;
Import javax.persistence.Table;
Import javax.persistence.Version;
@Entity
@Table (name = "T_concurrency") public
class Concurrency {
@Id
private int Id;
@Version
private int Version;
public int getId () {
return ID;
}
public void setId (int id) {
this.id = ID;
}
public int GetCount () {
return count;
}
public void SetCount (int count) {
This.count = count;
}
@Column
private int count;
public int getversion () {
return version;
}
public void setversion (int version) {
this.version = version;
}
}
3.dao
@Transactional (rollbackfor = runtimeexception.class,timeout=10)
@Override public
void subtract (int id) { Session
session = NULL;
try {
session = This.gethibernatetemplate (). Getsessionfactory (). Getcurrentsession ();
Query query = Session.createquery ("From Concurrency as u where u.id = '" + ID + "'");
Concurrency C = new Concurrency ();
c = (Concurrency) query.uniqueresult ();
if (C.getcount () > 0) {
//The first kind does not, not by Hibernate management, hibernate three states in line with, the direct HQL update optimistic lock not effective
//sqlquery sqlquery = Session.createsqlquery ("Update t_concurrency set count=count-1 where id = '" + ID + "'");
Sqlquery.executeupdate ();
C.setcount (C.getcount ()-1);
}
} catch (RuntimeException re) {
throw new runtimeexception ();
} finally {
if (session! = NULL && sess Ion.isopen ()) {
session.flush ();
Session.clear ();}}}