hibernate悲观锁例子

来源:互联网 发布:如何网络恢复mac系统 编辑:程序博客网 时间:2024/05/08 14:15
@Transactional(rollbackFor = RuntimeException.class)@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 + "'");query.setLockOptions(LockOptions.UPGRADE); //悲观锁//如果把setLockOptions换成setLockMode,表就无法锁定,打印出的sql语句也没有for update字段,不知道为什么//query.setLockMode("u", LockMode.PESSIMISTIC_WRITE);Concurrency c = new Concurrency();c = (Concurrency) query.uniqueResult();if (c.getCount() > 0) {SQLQuery sqlQuery = session.createSQLQuery("update t_concurrency set count=count-1 where id = '"+ id + "'");sqlQuery.executeUpdate();}} catch (RuntimeException re) {throw new RuntimeException();} finally {if (session != null && session.isOpen()) {session.flush();session.clear();}}}

0 0
原创粉丝点击