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(); } }
参考:
- SpringBoot事务注解@Transactional(在 控制器上设置事务
@Transactional
)