除了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://www.javacui.com/Framework/224.html 的代码。这里直接在Action层直接做代码示例,并使用注解进行属性注入:
首先编辑applicationContext.xml,配置数据库连接属性:<?xml version="1.0" encoding="UTF-8"?>
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">
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内做异常捕捉,否则无法控制事物。