PHP笔记网

革命尚未成功,同志仍须努力下载JDK17

作者:Albert.Wen  添加时间:2022-05-26 00:06:12  修改时间:2024-11-15 23:07:15  分类:06.Java框架/系统  编辑

PHP开发中,使用事务 的参考代码:

/**
 * 博客管理模块
 */
class BlogController extends BaseController {
	$res = Result::instance()->fail();

	$blogId = request_get_param('blogId', '');
	if (empty($blogId)) {
		$res->setMsg('参数错误');
		$res->outAjax();
	}

	// “开启”事务
	BlogModel::instance()->startTrans();
	
	try {
		$res = BlogManageService::instance()->delBlog($blogId);
	} catch (\Exception $e) {
		//“回滚”事务
		BlogModel::instance()->rollback();
		$res->setMsg("系统异常:" . $e->getMessage())->outAjax();
	}
	
	if ($res->isSuccess()) {
		// “提交”事务
		BlogModel::instance()->commit();
		$url = request_get_param('backUrl', url('admin/Blog/blogList'));
		$res->setUrl($url);
	} else {
		//“回滚”事务
		BlogModel::instance()->rollback();
	}

	$res->outAjax();
}

Java开发中,使用事务 参考代码:

@Controller
public class UserController extends BaseController {
	@Resource
    private IUserService iUserService;
	
	@ResponseBody
    @RequestMapping(UrlConst.User_addUserSubmit)
    @Transactional(rollbackFor = Exception.class)
    public String addUserSubmit(Model model, AddUserDTO addUserDTO) {
        Result<Object> res = iUserService.addUser(addUserDTO);
        if (res.isOk()) {
            res.setUrl(UrlConst.User_admin);
        } else {
            // 回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return res.outAjax();
    }
}

 

 

参考: