hibernate乐观锁例子

来源:互联网 发布:四川大学网络与新媒体 编辑:程序博客网 时间:2024/05/12 18:16

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 {@Idprivate int id;    @Versionprivate 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;}@Columnprivate int count;public int getVersion() {return version;}public void setVersion(int version) {this.version = version;}}

3.dao

@Transactional(rollbackFor = RuntimeException.class,timeout=10)@Overridepublic 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();}}}


0 0
原创粉丝点击