`
cuisuqiang
  • 浏览: 3954241 次
  • 性别: Icon_minigender_1
  • 来自: 北京
博客专栏
3feb66c0-2fb6-35ff-968a-5f5ec10ada43
Java研发技术指南
浏览量:3665215
社区版块
存档分类
最新评论

Spring 编程事物管理

    博客分类:
  • SSH
阅读更多

除了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&amp;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同步!

2
1
分享到:
评论
4 楼 cuisuqiang 2014-07-17  
Chunxian 写道
他其实想说你的博客里面有错别字。

注意,不要再doInTransaction内做异常捕捉,否则无法控制事物。

你真仔细哈
3 楼 Chunxian 2014-07-17  
他其实想说你的博客里面有错别字。

注意,不要再doInTransaction内做异常捕捉,否则无法控制事物。
2 楼 cuisuqiang 2014-04-24  
huchiwei 写道
想问,此事物是我理解的事务么

你理解的事物是什么事物?
1 楼 huchiwei 2014-04-24  
想问,此事物是我理解的事务么

相关推荐

    spring 自定义事务管理器,编程式事务,声明式事务@Transactional使用

    本教程将深入探讨如何在Spring中实现自定义事务管理器、编程式事务处理以及声明式事务`@Transactional`的使用。 首先,让我们了解事务管理的基本概念。事务是一组数据库操作,这些操作要么全部执行,要么全部回滚,...

    Spring事务管理Demo

    在Spring框架中,事务管理是核心特性之一,它允许开发者以声明式或编程式的方式处理应用中的事务。Spring事务管理的目的是确保数据的一致性和完整性,尤其是在多操作、多资源的环境中。本Demo将深入探讨Spring如何...

    spring编程式事务实现

    1. **Spring编程式事务管理**: 编程式事务管理允许开发者在代码中直接控制事务的开始、提交、回滚等操作。这种方式提供了更大的灵活性,但可能导致事务管理代码分散在整个应用中,增加维护难度。通常,这种方式...

    全面分析 Spring 的编程式事务管理及声明式事务管理

    本文将全面分析Spring中的编程式事务管理和声明式事务管理,旨在帮助开发者深入理解这两种事务管理方式,并在实际项目中合理选择。 **编程式事务管理** 编程式事务管理是通过代码直接控制事务的开始、提交、回滚等...

    spring声明事务,编程事务实现

    Spring 声明事务、编程事务实现 Spring 声明事务是指使用 Spring 框架来管理事务,实现事务控制。声明式事务管理是建立在 AOP 之上的,它的本质是对方法前后进行拦截,然后在目标方法开始之前创建或者加入一个事务...

    全面分析_Spring_的编程式事务管理及声明式事务管理

    本教程将深入探讨 Spring 的编程式事务管理和声明式事务管理,帮助你理解这两种方式的差异与应用场景。 首先,编程式事务管理依赖于编程的方式显式地控制事务的开始、提交、回滚等操作。它通过实现 `...

    实验 spring 声明事务

    实验 "Spring 声明事务" 是 Java 高级编程中的一个重要环节,旨在让学生掌握 Spring 框架中声明式事务管理的配置和使用。在实际应用中,事务管理是确保数据一致性、完整性和可靠性的关键组件。Spring 提供了声明式...

    Spring的事务管理小案例

    Spring的事务管理分为编程式事务管理和声明式事务管理两种方式。编程式事务管理需要开发者手动编写事务管理代码,虽然灵活但易出错,且侵入性强。声明式事务管理则是通过配置或注解来声明事务边界,更加简洁且易于...

    Spring 声明式事务和Spring 编程式事务

    Spring 声明式事务和Spring 编程式事务

    spring事务管理5种方法

    在IT行业中,Spring框架是Java企业级应用开发的首选,其强大的事务管理功能是它的一大亮点。本篇文章将深入探讨Spring事务管理的五种方法,旨在帮助开发者更好地理解和运用这一核心特性。 首先,我们来了解什么是...

    spring3.0两种事务管理配置

    Spring 中的事务管理可以分为两种:编程式事务管理和声明式事务管理。编程式事务管理是指通过编程的方式来管理事务,而声明式事务管理是指通过配置的方式来管理事务。 事务管理的隔离级别 Spring 中的事务管理提供...

    spring_事务管理(实例代码)

    在Spring框架中,事务管理分为编程式事务管理和声明式事务管理两种方式。 一、编程式事务管理 编程式事务管理允许开发者在代码中显式地开始、提交、回滚事务。这种方式虽然灵活,但会使得业务代码变得复杂,不易...

    Spring事务管理开发必备jar包

    2. **Spring事务管理**:Spring提供了两种事务管理方式,即编程式事务管理和声明式事务管理。编程式事务管理通过TransactionTemplate或直接调用PlatformTransactionManager接口的方法来管理事务,而声明式事务管理则...

    spring JDBC事务管理

    在Spring框架中,事务管理主要分为编程式事务管理和声明式事务管理两种: 1. **编程式事务管理**:这种方式要求开发者在代码中显式地开始、提交或回滚事务。通常通过`PlatformTransactionManager`接口实现,例如`...

    spring hibernate 事务管理学习笔记(一)

    同时,Spring的事务管理机制是其核心功能之一,支持编程式和声明式两种方式,使得开发者可以方便地控制事务的边界。 其次,Hibernate是Java领域最流行的ORM(Object-Relational Mapping)框架,它简化了数据库操作...

    spring_tx编程式事务代码

    Spring提供了多种事务管理方式,其中编程式事务管理和声明式事务管理是两种主要的模式。编程式事务管理允许开发者通过代码来精确控制事务的边界,而`TransactionTemplate`就是Spring为编程式事务管理提供的一种便捷...

    spring 事务管理的理解

    Spring 提供了两种事务管理方式:编程式事务管理和声明式事务管理。 1. 编程式事务管理:这是通过编写代码来控制事务的开始、提交和回滚。Spring 提供了PlatformTransactionManager接口,如...

Global site tag (gtag.js) - Google Analytics