`

使用Spring的事务模板

阅读更多

整体的工程代码跟上一篇日志的工程差不多。

服务类StudentService.java的代码如下:

package com.mysrc.service;

import java.sql.Date;
import java.util.List;

import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import com.mysrc.dao.StudentDao;
import com.mysrc.entity.Student;

public class StudentService {
	private StudentDao dao;
	private TransactionTemplate transactionTemplate;

	public void setDao(StudentDao dao) {
		this.dao = dao;
	}

	public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
		this.transactionTemplate = transactionTemplate;
	}

	public void doLogic1() {
		transactionTemplate.execute(new TransactionCallbackWithoutResult() {
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				try {
					doComplexLogic();
				} catch (Exception ex) {
					// 通过调用 TransactionStatus 对象的 setRollbackOnly() 方法来回滚事务。
					status.setRollbackOnly();
					ex.printStackTrace();
				}
			}
		});
	}

	public String doLogic2() {
		return transactionTemplate.execute(new TransactionCallback<String>() {
			public String doInTransaction(TransactionStatus status) {
				String result = "success";
				try {
					doComplexLogic();
				} catch (Exception e) {
					status.setRollbackOnly();
					e.printStackTrace();
					result = "fail";
				}
				return result;
			}
		});
	}

	public void doComplexLogic() {

		// select
		List<Student> list = dao.getAllStudent();
		for (Student student : list) {
			System.out.println(student);
		}

		// update
		Student student = list.get(0);
		student.setName("dianping..");
		dao.updateStudent(student);
		System.out.println("did update temporarily...");

		// int a = 9 / 0; // 遇到异常

		int b = 2;
		if (b > 1) {
			throw new CustomRuntimeException();
		}

		// insert
		student = new Student();
		student.setName("hello");
		student.setBirth(new Date(354778));
		student.setScore(78.9f);
		dao.addStudent(student);
		System.out.println("did insert...");

		// delete
		dao.deleteStudent(3);
		System.out.println("did delete...");
	}

}

 和上两篇日志不同的是,这儿不仅注入了dao,而且注入了一个transactionTemplate。这里TransactionTemplate模板类使用两种回调接口:TransactionCallback和TransactionCallbackWithoutResult。从字面就可以知道一个是不带返回值的,而另一个可以给出一个返回值。这里用到的transactionTemplate在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:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"
	xmlns:tx="http://www.springframework.org/schema/tx">

	<bean id="basicDataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="url"
			value="jdbc:mysql://127.0.0.1:3306/mytestdb?characterEncoding=utf8" />
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="username" value="root" />
		<property name="password" value="123456" />
		<property name="maxActive" value="100" />
		<property name="maxIdle" value="30" />
		<property name="maxWait" value="1000" />
		<property name="validationQuery" value="select 1" />
	</bean>
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<constructor-arg name="dataSource" ref="basicDataSource">
		</constructor-arg>
	</bean>
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager ">
		<property name="dataSource">
			<ref bean="basicDataSource" />
		</property>
	</bean>

	<bean id="studentDao" class="com.mysrc.dao.StudentDao">
		<property name="jdbcTemplate">
			<ref bean="jdbcTemplate" />
		</property>
	</bean>

	<bean id="studentService" class="com.mysrc.service.StudentService">
		<property name="dao" ref="studentDao" />
		<property name="transactionTemplate" ref="aTransactionTemplate" />
	</bean>

	<bean id="aTransactionTemplate"
		class="org.springframework.transaction.support.TransactionTemplate">
		<property name="transactionManager" ref="transactionManager" />
		<property name="propagationBehaviorName" value="PROPAGATION_NESTED" />
		<property name="timeout" value="1000" />
		<property name="isolationLevelName" value="ISOLATION_READ_UNCOMMITTED" />
	</bean>

</beans>

 在TransactionTemplate的bean声明中,也可以添加timeout,isolation等配置。

测试类的代码如下:

package com.mysrc.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.mysrc.service.StudentService;

public class MyTester {

	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				"applicationContext.xml");
		StudentService studentService = (StudentService) context
				.getBean("studentService");
		studentService.doLogic1();
		String rs = studentService.doLogic2();
		System.out.println(rs);
	}

}

  eclipse工程文件在附件中。。

分享到:
评论

相关推荐

    30. Spring事务模板及afterCommit存在的坑_V20240225.pdf

    30. Spring事务模板及afterCommit存在的坑_V20240225

    spring事务

    spring事务模板的使用,值得参考,让人更能使用到SSH框架综合的事务

    Spring声明式事务配置模板2.x

    Spring声明式事务配置模板2.x;提供通用的配置,系统对一些朋友有用。

    spring编程式事务实现

    演示了spring编程式事务的实现,通过TransactionTemplate模板进行事务控制

    spring_tx编程式事务代码

    Spring为了简化事务管理的代码:提供了模板类 TransactionTemplate,所以手动编程的方式来管理事务,只需要使用该模板类即可

    Spring.NET学习笔记17——事务传播行为(基础篇)代码下载

    Spring.NET事务配置模板。 原文出处:http://www.cnblogs.com/GoodHelper/archive/2009/11/16/SpringNet_Transaction.html

    springMVC + Hibernate 工程模板

    spring配置式事务管理(jdk动态代理,每个service必须对应一个接口) BaseService里注入BaseDao 和transactionTemplate(用于编程式事务处理,只用于特殊需要,因为已经存在配置式事务,一般符合命名的方法会自动...

    Spring+3.x企业应用开发实战光盘源码(全)

     第10章:对实际应用中Spring事务管理各种疑难问题进行透彻的剖析,让读者对Spring事务管理不再有云遮雾罩的感觉。  第11章:讲解了如何使用Spring JDBC进行数据访问操作,我们还重点讲述了LOB字段处理、主键产生...

    spring jar 包详解

    可以找到使用Spring ApplicationContext特性时所需的全部类,JDNI所需的全部类,UI方面的用来与模板(Templating)引擎如 Velocity、FreeMarker、JasperReports集成的类,以及校验Validation方面的相关类。...

    Spring 2.0 开发参考手册

    6.8.4. 在Spring应用中使用AspectJ Load-time weaving(LTW) 6.9. 其它资源 7. Spring AOP APIs 7.1. 简介 7.2. Spring中的切入点API 7.2.1. 概念 7.2.2. 切入点实施 7.2.3. AspectJ切入点表达式 7.2.4. ...

    spring.doc

    5.1.8.2Spring事务的传播属性 117 5.1.8.3Spring事务的隔离级别 117 拓展: 118 5.1.8.4以XML配置的 形式 119 拓展: 120 5.1.8.5以注解方式配置 125 拓展: 127 5.1.9使用CGLIB以XML形式配置事务 130 5.2 Spring+...

    基于SpringCloud开发的在线教育系统

    业务层:Spring IOC、Aop事务控制、Spring Task任务调度、Feign、Ribbon、Spring AMQP、Spring Data Redis等。 控制层:Spring MVC、FastJSON、RestTemplate、Spring Security Oauth2+JWT等 微服务治理:Eureka、...

    Spring-Reference_zh_CN(Spring中文参考手册)

    6.8.1. 在Spring中使用AspectJ来为domain object进行依赖注入 6.8.1.1. @Configurable object的单元测试 6.8.1.2. 多application context情况下的处理 6.8.2. Spring中其他的AspectJ切面 6.8.3. 使用Spring IoC来...

    Spring开发指南

    事务管理 持久层封装 JDBC Hibernate in Spring ibatis in Spring Aspect Oriented Programming AOP 概念 AOP in Spring Dynamic Proxy 与Spring AOP CGLib 与 Spring AOP AOP 应用 DAO Support ...

    spring in action英文版

     1.1 为什么使用Spring  1.1.1 J2EE开发者的一天  1.1.2 Spring的承诺  1.2 Spring是什么  1.3 开始Spring之旅  1.4 理解反向控制  1.4.1 依赖注入  1.4.2 IoC应用  1.4.3 企业级应用中的...

    Spring中文帮助文档

    6.8.1. 在Spring中使用AspectJ进行domain object的依赖注入 6.8.2. Spring中其他的AspectJ切面 6.8.3. 使用Spring IoC来配置AspectJ的切面 6.8.4. 在Spring应用中使用AspectJ加载时织入(LTW) 6.9. 更多资源 7...

    Spring.3.x企业应用开发实战(完整版).part2

    10.5.1 Spring事务管理器的应对 10.5.2 Hibernate+Spring JDBC混合框架的事务管理 10.6 特殊方法成漏网之鱼 10.6.1 哪些方法不能实施Spring AOP事务 10.6.2 事务增强遗漏实例 10.7 数据连接泄漏 10.7.1 底层连接资源...

    Spring API

    6.8.1. 在Spring中使用AspectJ进行domain object的依赖注入 6.8.2. Spring中其他的AspectJ切面 6.8.3. 使用Spring IoC来配置AspectJ的切面 6.8.4. 在Spring应用中使用AspectJ加载时织入(LTW) 6.9. 更多资源 7...

    spring boot 全面的样例代码

    - chapter4-3-2:[使用Spring Session(未完成)] #### 缓存支持 - chapter4-4-1:[注解配置与EhCache使用](http://blog.didispace.com/springbootcache1/) - chapter4-4-2:[使用Redis做集中式缓存]...

Global site tag (gtag.js) - Google Analytics