spring+hibernate事务的两种方式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/kouwoo/article/details/50379862

1.如果session的获取方式是session = this.getSession();这样的,可以用标签或者代码2种方式

  (1)标签方式

    

	@Transactional(rollbackFor = RuntimeException.class)
	@Override
	public void subtract(int id) {
		
		Session session = null;
		
		try {
			session = this.getSession();

			Query query = session.createQuery("from Concurrency u where u.id = '" + id + "'");

			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();
			}

			int i=1/0;//抛出异常
			
		} catch (RuntimeException re) {
			
			throw new RuntimeException();
			
		} finally {
			if (session != null && session.isOpen()) {
				session.flush();
				session.clear();
			}
		}
	}
 

   (2)代码方式 

	@Override
	public void subtract(int id) {
		
		Transaction ts = null;
		Session session = null;
		
		try {
			session = this.getSession();

			ts = session.beginTransaction();

			Query query = session.createQuery("from Concurrency u where u.id = '" + id + "'");

			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();
			}

			int i=1/0;//抛出异常
			ts.commit();
			
		} catch (RuntimeException re) {
			if (ts != null) {
				ts.rollback();
			}
			throw new RuntimeException();
			
		} finally {
			if (session != null && session.isOpen()) {
				session.flush();
				session.clear();
			}
		}
	}

2.如果session的获取方式是session = this.getHibernateTemplate().getSessionFactory().getCurrentSession();的方式

那么就只能用标签的方式了,不然就会报异常

展开阅读全文

没有更多推荐了,返回首页