---
title: "Spring 注解学习手札（五） 业务层事务处理"
author: "wxyfighting"
date: "2013-06-12T09:13:00Z"
tags: []
slug: "spring"
draft: false
lastmod: "2013-06-12T14:32:10Z"
id: 1885591
url: "https://wxyfighting.iteye.com/blog/1885591"
---

这里将用到以下几个包：

引用

aopalliance-1.0.jar  
commons-collections.jar  
commons-dbcp.jar  
commons-logging-1.1.1.jar  
commons-pool.jar  
jstl.jar  
log4j-1.2.15.jar  
mysql-connector-java-5.1.6-bin.jar  
spring-aop-2.5.6.jar  
spring-beans-2.5.6.jar  
spring-context-2.5.6.jar  
spring-context-support-2.5.6.jar  
spring-core-2.5.6.jar  
spring-jdbc-2.5.6.jar  
spring-tx-2.5.6.jar  
spring-web-2.5.6.jar  
spring-webmvc-2.5.6.jar  
standard.jar

主要增加了spring-aop-2.5.6.jar的AOP支持包！

之前我们在AccountService中加入了注解@Transactional标签，但是要想要真正发挥事务作用，还需要一些配置。  
主要需要调整dao.xml文件  
dao.xml-事务管理

Xml代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

1. &lt;bean
2. id="transactionManager"
3. class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
4. p:dataSource-ref="dataSource"/&gt;
5. &lt;tx:annotation-driven
6. transaction-manager="transactionManager"/&gt;

细化一下AccountService接口方法  
AccountService.java

Java代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

01. /\**
02. \*2010-1-23
03. \*/
04. packageorg.zlex.spring.service;
05. importorg.springframework.dao.DataAccessException;
06. importorg.springframework.transaction.annotation.Transactional;
07. importorg.zlex.spring.domain.Account;
08. /\**
09. \*账户业务接口
10. \*
11. \*@author&lt;ahref="mailto:zlex.dongliang@gmail.com"&gt;梁栋&lt;/a&gt;
12. \*@version1.0
13. \*@since1.0
14. \*/
15. publicinterfaceAccountService{
16. /\**
17. \*获得账户
18. \*
19. \*@paramusername
20. \*@parampassword
21. \*@return
22. \*/
23. @Transactional(readOnly=true)
24. Accountread(Stringusername,Stringpassword);
25. /\**
26. \*获得账户
27. \*
28. \*@paramid
29. \*@return
30. \*/
31. @Transactional(readOnly=true)
32. Accountread(intid);
33. /\**
34. \*注册用户
35. \*
36. \*@paramaccount
37. \*@return
38. \*/
39. @Transactional(readOnly=false,rollbackFor=DataAccessException.class)
40. Accountregister(Accountaccount);
41. }

这里我把注解@Transactional调整到了具体的方法上，也就是说这样写的话，凡是加入注解的标注的方法都属于事务配置！  
Account register(Account account);用做用户注册作用！![](http://snowolf.iteye.com/images/smiles/icon_biggrin.gif)  
@Transactional(readOnly = true)只读属性  
@Transactional(readOnly = false, rollbackFor = DataAccessException.class)只读关闭，遇到DataAccessException异常回滚！如果不对异常进行处理，该异常将一直向上层抛出，直至抛出到页面！  
如果你的Eclipse集成了SpringIDE，你可以观察一下这时的xml配置文件和AccoutServiceImpl.java的变化！![](http://snowolf.iteye.com/images/smiles/icon_biggrin.gif)  
![](http://dl.iteye.com/upload/attachment/203124/fd670ed5-7ae1-33d4-82cc-7e7e5f2d3186.jpg)  
![](http://dl.iteye.com/upload/attachment/203126/4b92af20-9f2f-3fef-817b-3c3f5a0e4e2f.jpg)  
这次，来个用户注册功能演示，故意在某个位置制造一个异常，看看是否正常回滚！![](http://snowolf.iteye.com/images/smiles/icon_biggrin.gif)  
先看注册控制器  
RegisterController.java

Java代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

01. /\**
02. \*2010-2-4
03. \*/
04. packageorg.zlex.spring.controller;
05. importjava.text.DateFormat;
06. importjava.text.SimpleDateFormat;
07. importjava.util.Date;
08. importorg.springframework.beans.factory.annotation.Autowired;
09. importorg.springframework.beans.propertyeditors.CustomDateEditor;
10. importorg.springframework.stereotype.Controller;
11. importorg.springframework.ui.ModelMap;
12. importorg.springframework.web.bind.WebDataBinder;
13. importorg.springframework.web.bind.annotation.InitBinder;
14. importorg.springframework.web.bind.annotation.ModelAttribute;
15. importorg.springframework.web.bind.annotation.RequestMapping;
16. importorg.springframework.web.bind.annotation.RequestMethod;
17. importorg.zlex.spring.domain.Account;
18. importorg.zlex.spring.service.AccountService;
19. /\**
20. \*用户注册控制器
21. \*
22. \*@author&lt;ahref="mailto:zlex.dongliang@gmail.com"&gt;梁栋&lt;/a&gt;
23. \*@version1.0
24. \*@since1.0
25. \*/
26. @Controller
27. @RequestMapping(value="/register.do")
28. publicclassRegisterController{
29. @Autowired
30. privateAccountServiceaccountService;
31. @InitBinder
32. publicvoidinitBinder(WebDataBinderbinder){
33. //忽略字段绑定异常
34. //binder.setIgnoreInvalidFields(true);
35. DateFormatformat=newSimpleDateFormat("yyyy-MM-dd");
36. binder.registerCustomEditor(Date.class,"birthday",
37. newCustomDateEditor(format,true));
38. }
39. @RequestMapping(method=RequestMethod.GET)
40. publicStringinitForm(ModelMapmodel){
41. Accountaccount=newAccount();
42. model.addAttribute("account",account);
43. //直接跳转到登录页面
44. return"account/register";
45. }
46. @RequestMapping(method=RequestMethod.POST)
47. protectedStringsubmit(@ModelAttribute("account")Accountaccount){
48. intid=accountService.register(account).getId();
49. //跳转到用户信息页面
50. return"redirect:profile.do?id="+id;
51. }
52. }

@InitBinder用于表单自定义属性绑定。这里我们要求输入一个日期格式的生日。  
@RequestMapping(method = RequestMethod.GET)用于初始化页面。  
@RequestMapping(method = RequestMethod.POST)用于提交页面。  
再看注册页面  
register.jsp

Jsp代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

01. &lt;html&gt;
02. &lt;head&gt;
03. &lt;metahttp-equiv="Content-Type"content="text/html;charset=UTF-8"&gt;
04. &lt;title&gt;注册&lt;/title&gt;
05. &lt;linkrel="stylesheet"type="text/css"href="css/style.css"/&gt;
06. &lt;scripttype="text/javascript"src="js/calendar.js"&gt;&lt;/script&gt;
07. &lt;/head&gt;
08. &lt;body&gt;
09. &lt;fieldset&gt;&lt;legend&gt;用户注册&lt;/legend&gt;&lt;form:form
10. commandName="account"&gt;
11. &lt;ul&gt;
12. &lt;li&gt;&lt;form:labelpath="username"&gt;用户名:&lt;/form:label&gt;&lt;form:input
13. path="username"/&gt;&lt;/li&gt;
14. &lt;li&gt;&lt;form:labelpath="password"&gt;密码:&lt;/form:label&gt;&lt;form:password
15. path="password"/&gt;&lt;/li&gt;
16. &lt;li&gt;&lt;form:labelpath="birthday"&gt;生日:&lt;/form:label&gt;&lt;form:input
17. path="birthday"onfocus="showDate(this);"/&gt;&lt;/li&gt;
18. &lt;li&gt;&lt;form:labelpath="email"&gt;Email:&lt;/form:label&gt;&lt;form:input
19. path="email"/&gt;&lt;/li&gt;
20. &lt;li&gt;
21. &lt;buttontype="submit"&gt;注册&lt;/button&gt;
22. &lt;buttontype="reset"&gt;重置&lt;/button&gt;
23. &lt;/li&gt;
24. &lt;/ul&gt;
25. &lt;/form:form&gt;&lt;/fieldset&gt;
26. &lt;/body&gt;
27. &lt;/html&gt;

这里我用了一个JavaScript日期控制标签：

Html代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

1. &lt;scripttype="text/javascript"src="js/calendar.js"&gt;&lt;/script&gt;

使用起来就像是这样：  
![](http://dl.iteye.com/upload/attachment/203135/7c6004e8-4fe6-3520-829e-fca37ae0a597.jpg)  
非常好用！！！![](http://snowolf.iteye.com/images/smiles/icon_idea.gif)当然，你完全可以使用JE上的那个JS控件！  
接下来稍微调整一下AccountService接口及其实现AccountServiceImpl  
AccountService.java

Java代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

01. publicinterfaceAccountService{
02. //省略
03. /\**
04. \*注册用户
05. \*
06. \*@paramaccount
07. \*@return
08. \*/
09. @Transactional(readOnly=false,rollbackFor=DataAccessException.class)
10. Accountregister(Accountaccount);
11. //省略
12. }

Java代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

01. @Service
02. publicclassAccountServiceImplimplementsAccountService{
03. @Autowired
04. privateAccountDaoaccountDao;
05. //省略
06. @Override
07. publicAccountregister(Accountaccount){
08. accountDao.create(account);
09. returnaccountDao.read(account.getUsername());
10. }
11. }

为了在插入一条记录后获得当前用户的主键，我们还得这么玩！![](http://snowolf.iteye.com/images/smiles/icon_smile.gif)的确有点雷人～  
从架构考虑，这是符合业务要求的实现！如果用iBatis或者Hibernate，这个问题就有数据库一次IO处理完成了！![](http://snowolf.iteye.com/images/smiles/icon_biggrin.gif)  
再看看AccountDao接口及其实现AccountDaoImpl  
AccountDao.java

Java代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

01. publicinterfaceAccountDao{
02. //省略
03. /\**
04. \*构建用户记录
05. \*
06. \*@paramaccount
07. \*@return
08. \*/
09. voidcreate(Accountaccount);
10. }

AccountDaoImpl.java

Java代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

01. @Repository
02. publicclassAccountDaoImplimplementsAccountDao{
03. //省略
04. @Override
05. publicvoidcreate(Accountaccount){
06. Stringsql="INSERTINTOaccount(username,password,birthday,email)VALUES(?,?,?,?)";
07. jdbcTemplate.update(sql,newObject\[]{account.getUsername(),
08. account.getPassword(),account.getBirthday(),
09. account.getEmail()});
10. }
11. }

来个注册演示！![](http://snowolf.iteye.com/images/smiles/icon_smile.gif)  
注册：  
![](http://dl.iteye.com/upload/attachment/203145/b5f45576-0738-3cd4-85ac-970f776c0401.jpg)  
信息展示：  
![](http://dl.iteye.com/upload/attachment/203147/bac3722c-6f82-345c-aa31-07a144eb730e.jpg)  
来制造一起事故！![](http://snowolf.iteye.com/images/smiles/icon_lol.gif)  
先看看数据库目前的状况！  
![](http://dl.iteye.com/upload/attachment/203149/f4f24a9f-54e6-39cf-999b-7ef134a06fa9.jpg)  
在AccountDaoImpl中来个破坏！![](http://snowolf.iteye.com/images/smiles/icon_lol.gif)

Java代码[![收藏代码](http://snowolf.iteye.com/images/icon_star.png)]()

1. @Override
2. publicvoidcreate(Accountaccount){
3. Stringsql="INSERTINTOaccount(username,password,birthday,email)VALUES(?,?,?,?)";
4. jdbcTemplate.update(sql,newObject\[]{account.getUsername(),
5. account.getPassword(),account.getBirthday(),
6. account.getEmail()});
7. thrownewRecoverableDataAccessException("TEST");
8. }

我们强行在执行完Insert语句后抛出DataAccessException异常（RecoverableDataAccessException）！![](http://snowolf.iteye.com/images/smiles/icon_smile.gif)  
来个注册试试！  
![](http://dl.iteye.com/upload/attachment/203154/cd3fb4e4-7409-38e9-bd9f-010fe958d25b.jpg)  
点击提交看看返回的异常！![](http://snowolf.iteye.com/images/smiles/icon_smile.gif)  
![](http://dl.iteye.com/upload/attachment/203156/3a55b436-eebf-30ea-824c-2c750fb905a8.jpg "点击查看原始大小图片")  
异常回滚生效！![](http://snowolf.iteye.com/images/smiles/icon_biggrin.gif)  
数据库中当然是什么都没有，我就不废话了！![](http://snowolf.iteye.com/images/smiles/icon_biggrin.gif)