java项目实战之Spring声明式事务利用运行时异常RuntimeException实现事务的回滚

首先来一段业务层事务的代码:

@Transactional
	public ShopExecution addShop(Shop shop, ImageHolder thumbnail) throws ShopOperationException {
		// 空值判断
		if (shop == null) {
			return new ShopExecution(ShopStateEnum.NULL_SHOP);
		}
		try {
			// 给店铺信息赋初始值
			shop.setEnableStatus(0);
			shop.setCreateTime(new Date());
			shop.setLastEditTime(new Date());
			// 添加店铺信息
			int effectedNum = shopDao.insertShop(shop);
			if (effectedNum <= 0) {
				throw new ShopOperationException("店铺创建失败");
			} else {
				if (thumbnail.getImage() != null) {
					// 存储图片
					try {
						addShopImg(shop, thumbnail);
					} catch (Exception e) {
						throw new ShopOperationException("addShopImg error:" + e.getMessage());
					}
					// 更新店铺的图片地址
					effectedNum = shopDao.updateShop(shop);
					if (effectedNum <= 0) {
						throw new ShopOperationException("更新图片地址失败");
					}
				}
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
			throw new ShopOperationException("addShop error:" + e.getMessage());
		}
		return new ShopExecution(ShopStateEnum.CHECK, shop);
	}

首先我们可以看到,它的第一行有一个@Transactional,在这里我们用的是声明式事务。然后在中间操作的时候,我们会扔出一些ShopOperationException,这是我们封装好的一个运行时异常,如果发生错误,就回滚了,这个异常定义为:

package com.teyu.mo2o.exceptions;

public class ShopOperationException extends RuntimeException {
	/**
	 * 
	 */
	private static final long serialVersionUID = 2361446884822298905L;

	public ShopOperationException(String msg) {
		super(msg);
	}
}

 

你可能感兴趣的:(项目实战)