1.在数据表中新建一个version字段,可以是int或者是bigint
2.在javabean中增加个version字段
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) {
//第一种不行的,没有被hibernate管理,hibernate三种状态符合才行,直接hql更新乐观锁不起效
//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 && session.isOpen()) {
session.flush();
session.clear();
}
}
}