java spring事务管理系统_Spring 编程事物管理

除了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内做异常捕捉,否则无法控制事物。

34a9fa48e2983eb29bfccb23aa3682b6.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值