使用Spring的事务模板_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > 使用Spring的事务模板

使用Spring的事务模板

 2014/7/17 22:10:04  tonlion2046  程序员俱乐部  我要评论(0)
  • 摘要:整体的工程代码跟上一篇日志的工程差不多。服务类StudentService.java的代码如下:packagecom.mysrc.service;importjava.sql.Date;importjava.util.List;importorg.springframework.transaction.TransactionStatus;importorg.springframework.transaction.support.TransactionCallback;importorg
  • 标签:模板 使用 Spring

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

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

class="java" name="code">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工程文件在附件中。。

  • MyTransactionTest.zip (5.7 MB)
  • 下载次数: 2
上一篇: 使用Spring的声明式事务----AOP方式 下一篇: 没有下一篇了!
发表评论
用户名: 匿名