除了Spring的DIST下的包外,加入:
commons-pool.jar commons-dbcp.jar mysql-connector-java-5.1.5-bin.jar
这里使用的是mysql数据库,在test库内创建表:
DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `age` int(11) DEFAULT NULL, `name` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
编程式事物相对声明式事物有些繁琐,但是还是有其独到的优点。编程式的事物管理可以清楚的控制事务的边界,自行控制事物开始、撤销、超时、结束等,自由控制事物的颗粒度。
借用Spring MVC 入门示例http://cuisuqiang.iteye.com/blog/2042931的代码。这里直接在Action层直接做代码示例,并使用注解进行属性注入:
首先编辑applicationContext.xml,配置数据库连接属性:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8" /> <property name="username" value="root" /> <property name="password" value="root" /> </bean> </beans>
Spring提供两种实现方式,使用PlatformTransactionManager或TransactionTemplate。
以下示例使用PlatformTransactionManager的实现类DataSourceTransactionManager来完成。
package test; import java.util.Date; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import org.springframework.web.bind.annotation.RequestMapping; // http://localhost:8080/spring/hello.do?user=java @org.springframework.stereotype.Controller public class HelloController{ private DataSourceTransactionManager transactionManager; private DefaultTransactionDefinition def; private JdbcTemplate jdbcTemplate; @SuppressWarnings("unused") // 使用注解注入属性 @Autowired private void setDataSource(DataSource dataSource){ jdbcTemplate = new JdbcTemplate(dataSource); transactionManager = new DataSourceTransactionManager(dataSource); // 事物定义 def = new DefaultTransactionDefinition(); // 事物传播特性 def.setPropagationBehavior(DefaultTransactionDefinition.PROPAGATION_REQUIRED); // def.setReadOnly(true); // 指定后会做一些优化操作,但是必须搭配传播特性,例如:PROPAGATION_REQUIRED,PROPAGATION_REQUIRES_NEW,PROPAGATION_NESTED // def.setTimeout(1000); // 合理的超时时间,有助于系统更加有效率 } @SuppressWarnings("deprecation") @RequestMapping("/hello.do") public String hello(HttpServletRequest request,HttpServletResponse response){ request.setAttribute("user", request.getParameter("user") + "-->" + new Date().toLocaleString()); TransactionStatus status = transactionManager.getTransaction(def); try { jdbcTemplate.update(" update user set age=age+1; "); // 发生异常 jdbcTemplate.update(" update user set age='test'; "); transactionManager.commit(status); } catch (Exception e) { transactionManager.rollback(status); } return "hello"; } }
也可以使用TransactionTemplate来实现,它需要一个TransactionManager实例,代码如下:
package test; import java.util.Date; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; import org.springframework.web.bind.annotation.RequestMapping; @org.springframework.stereotype.Controller public class HelloController{ private DataSourceTransactionManager transactionManager; private DefaultTransactionDefinition def; private JdbcTemplate jdbcTemplate; @SuppressWarnings("unused") @Autowired private void setDataSource(DataSource dataSource){ jdbcTemplate = new JdbcTemplate(dataSource); transactionManager = new DataSourceTransactionManager(dataSource); def = new DefaultTransactionDefinition(); def.setPropagationBehavior(DefaultTransactionDefinition.PROPAGATION_REQUIRED); } @SuppressWarnings({ "deprecation", "unchecked" }) @RequestMapping("/hello.do") public String hello(HttpServletRequest request,HttpServletResponse response){ request.setAttribute("user", request.getParameter("user") + "-->" + new Date().toLocaleString()); TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); Object obj = null; try { // 不需要返回值使用TransactionCallbackWithoutResultback obj = transactionTemplate.execute(new TransactionCallback(){ public Object doInTransaction(TransactionStatus arg0) { jdbcTemplate.update(" update user set age=age+1; "); // 发生异常 jdbcTemplate.update(" update user set age='test'; "); return 1; } }); } catch (Exception e) { e.printStackTrace(); } System.out.println(obj); return "hello"; } }
注意,不要再doInTransaction内做异常捕捉,否则无法控制事物。
请您到ITEYE网站看 java小强 原创,谢谢!
http://cuisuqiang.iteye.com/ !
自建博客地址:http://www.javacui.com/ ,内容与ITEYE同步!
相关推荐
本代码使用H2内存数据库演示spring事务使用,包括编程式事务,声明式事务@Transactional使用,自定义事务事务注解实现自定义事务管理器
演示了spring编程式事务的实现,通过TransactionTemplate模板进行事务控制
Spring 声明式事务和Spring 编程式事务
Spring 的事务管理是 Spring 框架中一个比较重要的知识点,该知识点本身并不复杂,只是由于其比较灵活,导致初学者很难把握。本教程从基础知识开始,详细分析了 Spring 事务管理的使用方法,为读者理清思路。
Java高级编程 实验报告 spring 声明事务 实验目的 掌握spring 声明式事务管理配置 实验环境 本实验采用本实验采用的eclipse或者 Myeclpse开发工具。Spring 4.0以上 Jdk1.7以上、oracle/mysql。
全面分析_Spring_的编程式事务管理及声明式事务管理,本教程假定您已经掌握了 Java 基础知识,并对 Spring 有一定了解。您还需要具备基本的事务管理的知识,比如:事务的定义,隔离级别的概念,等等。本文将直接使用...
spring编程式事务与声明式事务详解,超详细!
NULL 博文链接:https://konglx.iteye.com/blog/1836826
Spring事务管理.pdf 1.资料 2.本地事务与分布式事务 3.编程式模型 4.宣告式模型
编程语言+JAVAspring+事务管理+数据一致性**:这是一个关于JAVAspring编程语言的事务管理的数据一致性的资源,适合有一定JAVAspring基础的开发者。它介绍了JAVAspring的事务管理的概念、原理和作用,以及如何使用...
Spring为了简化事务管理的代码:提供了模板类 TransactionTemplate,所以手动编程的方式来管理事务,只需要使用该模板类即可
全面分析_Spring_的编程式事务管理及声明式事务管理.
Spring的事务框架将开发过程中事务管理相关的关注点进行适当的分离,并对这些关注点进行合 理的抽象,最终打造了一套使用方便,却功能强大的事务管理“利器”。通过Spring的事务框架,我 们可以按照统一的编程模型来...
spring编程式和声明式事务管理,事务放在dao,存演示版本!懂!
spring事务管理几种方式代码实例:涉及编程式事务,声明式事务之拦截器代理方式、AOP切面通知方式、AspectJ注解方式,通过不同方式实例代码展现,总结spring事务管理的一般规律,从宏观上加深理解spring事务管理特性...
全面分析Spring的编程式事务管理与声明式事务管理.doc
相信对于很多初学者或者使用者,都了解spring事务,但是具体细节,实现方式,都没有系统的概念或者无从下手,本人周末闲来无事,坐下总结,时间紧促,写的不周全的地方还请提出宝贵意见。
Spring将事务管理分成了两类: * 编程式事务管理 * 手动编写代码进行事务管理.(很少使用) * 声明式事务管理: * 基于TransactionProxyFactoryBean的方式.(很少使用) * 需要为每个进行事务管理的类,配置一个...
spring编程式事务与声明式事务详解[参照].pdf