<!-- 配置事務管理器 --> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> <!-- <property name="dataSource" ref="dataSource" />--> </bean> <!-- 啓用支持Annotation註解方式的事務管理 --> <tx:annotation-driven transaction-manager="transactionManager" />
1. 由spring框架自動化管理html
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. 手動提交事務spring
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; } }