`
hz_chenwenbiao
  • 浏览: 1014474 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

Spring 注解学习手札(五) 业务层事务处理

阅读更多

控制器层、持久层都有了一些介绍,剩下的就是业务层了!
业务层中的关键问题在于事务控制!Spring的注解式事务处理其实很简单!

相关参考:
Spring 注解学习手札(一) 构建简单Web应用
Spring 注解学习手札(二) 控制层梳理
Spring 注解学习手札(三) 表单页面处理
Spring 注解学习手札(四) 持久层浅析
Spring 注解学习手札(五) 业务层事务处理
Spring 注解学习手札(六) 测试

这里将用到以下几个包:

引用

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代码 复制代码
  1. <bean  
  2.     id="transactionManager"  
  3.     class="org.springframework.jdbc.datasource.DataSourceTransactionManager"  
  4.     p:dataSource-ref="dataSource" />  
  5. <tx:annotation-driven  
  6.     transaction-manager="transactionManager" />  
	<bean
		id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
		p:dataSource-ref="dataSource" />
	<tx:annotation-driven
		transaction-manager="transactionManager" />


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

Java代码 复制代码
  1. /**  
  2.  * 2010-1-23  
  3.  */  
  4. package org.zlex.spring.service;   
  5.   
  6. import org.springframework.dao.DataAccessException;   
  7. import org.springframework.transaction.annotation.Transactional;   
  8. import org.zlex.spring.domain.Account;   
  9.   
  10. /**  
  11.  * 账户业务接口  
  12.  *   
  13.  * @author <a href="mailto:zlex.dongliang@gmail.com">梁栋</a>  
  14.  * @version 1.0  
  15.  * @since 1.0  
  16.  */  
  17. public interface AccountService {   
  18.   
  19.     /**  
  20.      * 获得账户  
  21.      *   
  22.      * @param username  
  23.      * @param password  
  24.      * @return  
  25.      */  
  26.     @Transactional(readOnly = true)   
  27.     Account read(String username, String password);   
  28.   
  29.     /**  
  30.      * 获得账户  
  31.      *   
  32.      * @param id  
  33.      * @return  
  34.      */  
  35.     @Transactional(readOnly = true)   
  36.     Account read(int id);   
  37.   
  38.     /**  
  39.      * 注册用户  
  40.      *   
  41.      * @param account  
  42.      * @return  
  43.      */  
  44.     @Transactional(readOnly = false, rollbackFor = DataAccessException.class)   
  45.     Account register(Account account);   
  46. }  
/**
 * 2010-1-23
 */
package org.zlex.spring.service;

import org.springframework.dao.DataAccessException;
import org.springframework.transaction.annotation.Transactional;
import org.zlex.spring.domain.Account;

/**
 * 账户业务接口
 * 
 * @author <a href="mailto:zlex.dongliang@gmail.com">梁栋</a>
 * @version 1.0
 * @since 1.0
 */
public interface AccountService {

	/**
	 * 获得账户
	 * 
	 * @param username
	 * @param password
	 * @return
	 */
	@Transactional(readOnly = true)
	Account read(String username, String password);

	/**
	 * 获得账户
	 * 
	 * @param id
	 * @return
	 */
	@Transactional(readOnly = true)
	Account read(int id);

	/**
	 * 注册用户
	 * 
	 * @param account
	 * @return
	 */
	@Transactional(readOnly = false, rollbackFor = DataAccessException.class)
	Account register(Account account);
}


这里我把注解@Transactional调整到了具体的方法上,也就是说这样写的话,凡是加入注解的标注的方法都属于事务配置!
Account register(Account account);用做用户注册作用!
@Transactional(readOnly = true)只读属性
@Transactional(readOnly = false, rollbackFor = DataAccessException.class)只读关闭,遇到DataAccessException异常回滚!如果不对异常进行处理,该异常将一直向上层抛出,直至抛出到页面!
如果你的Eclipse集成了SpringIDE,你可以观察一下这时的xml配置文件和AccoutServiceImpl.java的变化!


这次,来个用户注册功能演示,故意在某个位置制造一个异常,看看是否正常回滚!
先看注册控制器
RegisterController.java

Java代码 复制代码
  1. /**  
  2.  * 2010-2-4  
  3.  */  
  4. package org.zlex.spring.controller;   
  5.   
  6. import java.text.DateFormat;   
  7. import java.text.SimpleDateFormat;   
  8. import java.util.Date;   
  9.   
  10. import org.springframework.beans.factory.annotation.Autowired;   
  11. import org.springframework.beans.propertyeditors.CustomDateEditor;   
  12. import org.springframework.stereotype.Controller;   
  13. import org.springframework.ui.ModelMap;   
  14. import org.springframework.web.bind.WebDataBinder;   
  15. import org.springframework.web.bind.annotation.InitBinder;   
  16. import org.springframework.web.bind.annotation.ModelAttribute;   
  17. import org.springframework.web.bind.annotation.RequestMapping;   
  18. import org.springframework.web.bind.annotation.RequestMethod;   
  19. import org.zlex.spring.domain.Account;   
  20. import org.zlex.spring.service.AccountService;   
  21.   
  22. /**  
  23.  * 用户注册控制器  
  24.  *   
  25.  * @author <a href="mailto:zlex.dongliang@gmail.com">梁栋</a>  
  26.  * @version 1.0  
  27.  * @since 1.0  
  28.  */  
  29. @Controller  
  30. @RequestMapping(value = "/register.do")   
  31. public class RegisterController {   
  32.   
  33.     @Autowired  
  34.     private AccountService accountService;   
  35.   
  36.     @InitBinder  
  37.     public void initBinder(WebDataBinder binder) {   
  38.         // 忽略字段绑定异常   
  39.         // binder.setIgnoreInvalidFields(true);   
  40.   
  41.         DateFormat format = new SimpleDateFormat("yyyy-MM-dd");   
  42.         binder.registerCustomEditor(Date.class"birthday",   
  43.                 new CustomDateEditor(format, true));   
  44.     }   
  45.   
  46.     @RequestMapping(method = RequestMethod.GET)   
  47.     public String initForm(ModelMap model) {   
  48.         Account account = new Account();   
  49.         model.addAttribute("account", account);   
  50.         // 直接跳转到登录页面   
  51.         return "account/register";   
  52.     }   
  53.   
  54.     @RequestMapping(method = RequestMethod.POST)   
  55.     protected String submit(@ModelAttribute("account") Account account) {   
  56.         int id = accountService.register(account).getId();   
  57.         // 跳转到用户信息页面   
  58.         return "redirect:profile.do?id=" + id;   
  59.     }   
  60. }  
/**
 * 2010-2-4
 */
package org.zlex.spring.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.zlex.spring.domain.Account;
import org.zlex.spring.service.AccountService;

/**
 * 用户注册控制器
 * 
 * @author <a href="mailto:zlex.dongliang@gmail.com">梁栋</a>
 * @version 1.0
 * @since 1.0
 */
@Controller
@RequestMapping(value = "/register.do")
public class RegisterController {

	@Autowired
	private AccountService accountService;

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		// 忽略字段绑定异常
		// binder.setIgnoreInvalidFields(true);

		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, "birthday",
				new CustomDateEditor(format, true));
	}

	@RequestMapping(method = RequestMethod.GET)
	public String initForm(ModelMap model) {
		Account account = new Account();
		model.addAttribute("account", account);
		// 直接跳转到登录页面
		return "account/register";
	}

	@RequestMapping(method = RequestMethod.POST)
	protected String submit(@ModelAttribute("account") Account account) {
		int id = accountService.register(account).getId();
		// 跳转到用户信息页面
		return "redirect:profile.do?id=" + id;
	}
}


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

Jsp代码 复制代码
  1. <html>   
  2. <head>   
  3. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">   
  4. <title>注册</title>   
  5. <link rel="stylesheet" type="text/css" href="css/style.css" />   
  6. <script type="text/javascript" src="js/calendar.js"></script>   
  7. </head>   
  8. <body>   
  9. <fieldset><legend>用户注册</legend><form:form   
  10.     commandName="account">   
  11.     <ul>   
  12.         <li><form:label path="username">用户名:</form:label><form:input   
  13.             path="username" /></li>   
  14.         <li><form:label path="password">密码:</form:label><form:password   
  15.             path="password" /></li>   
  16.         <li><form:label path="birthday">生日:</form:label><form:input   
  17.             path="birthday" onfocus="showDate(this);" /></li>   
  18.         <li><form:label path="email">Email:</form:label><form:input   
  19.             path="email" /></li>   
  20.         <li>   
  21.         <button type="submit">注册</button>   
  22.         <button type="reset">重置</button>   
  23.         </li>   
  24.     </ul>   
  25. </form:form></fieldset>   
  26. </body>   
  27. </html>  
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>注册</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script type="text/javascript" src="js/calendar.js"></script>
</head>
<body>
<fieldset><legend>用户注册</legend><form:form
	commandName="account">
	<ul>
		<li><form:label path="username">用户名:</form:label><form:input
			path="username" /></li>
		<li><form:label path="password">密码:</form:label><form:password
			path="password" /></li>
		<li><form:label path="birthday">生日:</form:label><form:input
			path="birthday" onfocus="showDate(this);" /></li>
		<li><form:label path="email">Email:</form:label><form:input
			path="email" /></li>
		<li>
		<button type="submit">注册</button>
		<button type="reset">重置</button>
		</li>
	</ul>
</form:form></fieldset>
</body>
</html>


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

Html代码 复制代码
  1. <script type="text/javascript" src="js/calendar.js"></script>  
<script type="text/javascript" src="js/calendar.js"></script>


使用起来就像是这样:

非常好用!!! 当然,你完全可以使用JE上的那个JS控件!
接下来稍微调整一下AccountService接口及其实现AccountServiceImpl
AccountService.java

Java代码 复制代码
  1. public interface AccountService {   
  2.     // 省略   
  3.     /**  
  4.      * 注册用户  
  5.      *   
  6.      * @param account  
  7.      * @return  
  8.      */  
  9.     @Transactional(readOnly = false, rollbackFor = DataAccessException.class)   
  10.     Account register(Account account);   
  11.     // 省略   
  12. }  
public interface AccountService {
	// 省略
	/**
	 * 注册用户
	 * 
	 * @param account
	 * @return
	 */
	@Transactional(readOnly = false, rollbackFor = DataAccessException.class)
	Account register(Account account);
	// 省略
}


Java代码 复制代码
  1. @Service  
  2. public class AccountServiceImpl implements AccountService {   
  3.   
  4.     @Autowired  
  5.     private AccountDao accountDao;   
  6.   
  7.     // 省略   
  8.   
  9.     @Override  
  10.     public Account register(Account account) {   
  11.         accountDao.create(account);   
  12.         return accountDao.read(account.getUsername());   
  13.     }   
  14. }  
@Service
public class AccountServiceImpl implements AccountService {

	@Autowired
	private AccountDao accountDao;

	// 省略

	@Override
	public Account register(Account account) {
		accountDao.create(account);
		return accountDao.read(account.getUsername());
	}
}


为了在插入一条记录后获得当前用户的主键,我们还得这么玩! 的确有点雷人~
从架构考虑,这是符合业务要求的实现!如果用iBatis或者Hibernate,这个问题就有数据库一次IO处理完成了!
再看看AccountDao接口及其实现AccountDaoImpl
AccountDao.java

Java代码 复制代码
  1. public interface AccountDao {   
  2.         // 省略   
  3.     /**  
  4.      * 构建用户记录  
  5.      *   
  6.      * @param account  
  7.      * @return  
  8.      */  
  9.     void create(Account account);   
  10. }  
public interface AccountDao {
        // 省略
	/**
	 * 构建用户记录
	 * 
	 * @param account
	 * @return
	 */
	void create(Account account);
}



AccountDaoImpl.java

Java代码 复制代码
  1. @Repository  
  2. public class AccountDaoImpl implements AccountDao {   
  3.         // 省略   
  4.   
  5.     @Override  
  6.     public void create(Account account) {   
  7.         String sql = "INSERT INTO account(username, password, birthday, email) VALUES(?,?,?,?)";   
  8.   
  9.         jdbcTemplate.update(sql, new Object[] { account.getUsername(),   
  10.                 account.getPassword(), account.getBirthday(),   
  11.                 account.getEmail() });   
  12.     }   
  13. }  
@Repository
public class AccountDaoImpl implements AccountDao {
        // 省略

	@Override
	public void create(Account account) {
		String sql = "INSERT INTO account(username, password, birthday, email) VALUES(?,?,?,?)";

		jdbcTemplate.update(sql, new Object[] { account.getUsername(),
				account.getPassword(), account.getBirthday(),
				account.getEmail() });
	}
}


来个注册演示!
注册:

信息展示:

来制造一起事故!
先看看数据库目前的状况!

在AccountDaoImpl中来个破坏!

Java代码 复制代码
  1. @Override  
  2.     public void create(Account account) {   
  3.         String sql = "INSERT INTO account(username, password, birthday, email) VALUES(?,?,?,?)";   
  4.   
  5.         jdbcTemplate.update(sql, new Object[] { account.getUsername(),   
  6.                 account.getPassword(), account.getBirthday(),   
  7.                 account.getEmail() });   
  8.   
  9.         throw new RecoverableDataAccessException("TEST");   
  10.     }  
@Override
	public void create(Account account) {
		String sql = "INSERT INTO account(username, password, birthday, email) VALUES(?,?,?,?)";

		jdbcTemplate.update(sql, new Object[] { account.getUsername(),
				account.getPassword(), account.getBirthday(),
				account.getEmail() });

		throw new RecoverableDataAccessException("TEST");
	}


我们强行在执行完Insert语句后抛出DataAccessException异常(RecoverableDataAccessException)!
来个注册试试!

点击提交看看返回的异常!

异常回滚生效!
数据库中当然是什么都没有,我就不废话了!

分享到:
评论

相关推荐

    Spring 注解学习手札(四) 持久层浅析

    在本篇《Spring注解学习手札(四)持久层浅析》中,我们将深入探讨Spring框架在持久层的应用,特别是如何通过注解简化数据库操作。Spring作为一个强大的轻量级框架,提供了丰富的功能来处理数据访问,使得开发者可以...

    Spring 注解学习手札(一) 构建简单Web应用

    在本篇《Spring注解学习手札(一)构建简单Web应用》中,我们将深入探讨如何使用Spring框架的注解来构建一个基本的Web应用程序。Spring框架是Java开发中的核心工具,尤其在企业级应用中广泛应用。它简化了依赖注入、...

    Spring 注解学习手札

    【Spring注解学习手札】 在现代Java Web开发中,Spring框架因其强大的功能和灵活性而备受推崇。Spring注解的引入极大地简化了配置文件,提高了开发效率。本篇将聚焦于Spring MVC中的注解,通过构建一个简单的Web...

    Spring 注解学习手札(二) 控制层梳理

    这篇“Spring注解学习手札(二)控制层梳理”主要聚焦于如何利用注解来构建和理解Spring MVC的控制层,即Controller。Spring MVC是Spring框架的一部分,专门用于处理Web应用程序的请求和响应。 一、@RestController...

    Spring 注解学习手札(三) 表单页面处理

    在本篇《Spring注解学习手札(三)表单页面处理》中,我们将深入探讨Spring框架中关于处理Web表单的关键注解和技术。在实际的Web开发中,表单处理是用户交互的重要组成部分,Spring提供了强大的支持,使得开发者能够...

    Spring 注解学习手札(六) 测试

    在本篇《Spring注解学习手札(六)——测试》中,我们将深入探讨Spring框架中的测试支持,尤其是如何利用注解进行单元测试和集成测试。Spring为开发者提供了丰富的注解,使得测试代码更加简洁、易读且易于维护。本文...

    Spring 注解学习手札(七) 补遗——@ResponseBody,@RequestBody,@PathVariable

    在Spring框架中,注解是实现轻量级、声明式编程的重要工具,极大地简化了代码并提高了可维护性。本文将深入探讨`@ResponseBody`、`@RequestBody`和`@PathVariable`这三个关键注解,它们在处理HTTP请求和响应中的作用...

    Spring 注解学习

    以上内容基于Snowolf的博客文章《Spring注解手札》系列,该系列文章详尽地介绍了Spring注解的使用,从构建简单的Web应用到控制层、表单处理、持久层以及事务管理和测试,覆盖了Spring注解的多个方面。通过这些实例,...

    Perl_学习手札

    在"Perl学习手札"中,你将深入学习如何构建和使用这些表达式,以及如何结合其他Perl函数进行更复杂的文本处理。 其次,Perl提供了丰富的内置数据结构,如数组、哈希(关联数组)和标量,使你能够有效地组织和操作...

    spring 的详细使用

    - "spring-reference.pdf" 和 "Spring注解手札.pdf" 可能是详细的 Spring 参考文档和注解指南,对于深入学习 Spring 极为有用。 以上内容只是 Spring 框架的冰山一角,想要精通 Spring,还需要通过阅读文档、实践...

    perl学习手札中文

    "Perl学习手札中文"是一份专为初学者设计的学习资料,旨在帮助读者快速掌握Perl语言的基础和高级特性。以下是对这些文件内容的概览: 1. **word.css**: 这个文件可能是样式表,用于定义文档中的排版和格式。在学习...

    perl学习手札(简体中文)_简信昌

    关于作者: 简信昌 “傲尔网”专案经理 博仲法律事务所资讯部门 台北Perl推广组 (Taipei.pm) 召集人 Newzilla召集人 目前专案: Open Source Foundry (OSSF) Newzilla 线上杂志 ...“Perl学习手札”

    Perl学习手札.chm

    Perl学习手札.chmPerl学习手札.chmPerl学习手札.chm

    hibernate学习手札.z03

    hibernate学习手札.z03

    Perl 学习手札.pdf

    ### Perl学习手札知识点概述 #### 1. 关于Perl - **1.1 Perl的历史**:Perl由Larry Wall在1987年创建,旨在为文本处理提供一种更强大的工具。随着时间的发展,Perl逐渐成为了脚本编程领域的领导者之一。 - **1.2 ...

    Perl 学习手札

    通过深入学习“Perl学习手札”,你可以系统地掌握这些概念,并逐步成长为一个熟练的Perl程序员。记住,实践是检验知识的最好方式,所以不仅要理解理论,还要动手编写代码,解决实际问题。祝你在Perl的学习之旅中取得...

    hibernate学习手札.z01

    hibernate学习手札.z01

    高级Perl编程(黑豹书)+学习手札

    学习这部分可以帮助读者熟练地进行数据库查询、事务处理和错误处理。 6. 并发和多线程:Perl支持线程编程,可以处理并发任务,提高程序性能。书中会介绍线程的创建、同步机制和死锁避免策略。 而《Perl_学习手札》...

Global site tag (gtag.js) - Google Analytics