hibernate悲观锁例子

	@Transactional(rollbackFor = RuntimeException.class)
	@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 + "'");
			
			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();
			}
		}
	}

你可能感兴趣的:(hibernate悲观锁例子)