1. 由spring框架自动化管理
public class ArticleAction { @Autowired private IArticleService articleService; @Autowired private IArticleClassService articleClassService; @RequestMapping({ "/jpatest1.htm"}) @Transactional(rollbackFor = Exception.class,propagation=Propagation.REQUIRED) public ModelAndView jpatest1(HttpServletRequest request){ ModelAndView mv = new JModelAndView("jpatest.html"); ArticleClass articleClass = this.articleClassService.getObjById(CommUtil.null2Long(163843)); articleClass.setClassName("特色服务2222"); this.articleClassService.update(articleClass); Article article = this.articleService.getObjByProperty("mark", "join111"); article.setTitle(article.getTitle()+"2222"); this.articleService.update(article); mv.addObject("status","transaction success"); return mv; } @RequestMapping({ "/jpatest2.htm"}) @Transactional public ModelAndView jpatest2(HttpServletRequest request){ ModelAndView mv = new JModelAndView("jpatest.html"); ArticleClass articleClass = this.articleClassService.getObjById(CommUtil.null2Long(163843)); articleClass.setClassName("特色服务2222"); this.articleClassService.update(articleClass); Article article = this.articleService.getObjByProperty("mark", "join111"); article.setTitle(article.getTitle()+"2222"); this.articleService.update(article); mv.addObject("status","transaction success"); return mv; } }
2. 手动提交事务
public class ArticleAction { @Autowired private IArticleService articleService; @Autowired private IArticleClassService articleClassService; /** * JpaTransactionManager事务管理 . */ @Resource(name = "transactionManager") private JpaTransactionManager tm; @RequestMapping({ "/jpatest.htm"}) @Transactional(value="transactionManager", rollbackFor = Exception.class) public ModelAndView jpatest(HttpServletRequest request){ ModelAndView mv = new JModelAndView("jpatest.html"); //事务开始 DefaultTransactionDefinition def = new DefaultTransactionDefinition(); def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); def.setTimeout(30); //事务状态 TransactionStatus status = tm.getTransaction(def); try { //此处写持久层逻辑 ArticleClass articleClass = this.articleClassService.getObjById(CommUtil.null2Long(163843)); articleClass.setClassName("特色服务2222"); this.articleClassService.update(articleClass); Article article = this.articleService.getObjByProperty("mark", "join111"); article.setTitle(article.getTitle()+"2222"); this.articleService.update(article); tm.commit(status); mv.addObject("status","transaction success"); } catch (Exception e) { System.out.println("出现异常,开始回滚"+e); if(!status.isCompleted()){ tm.rollback(status); } //throw e; } return mv; } }