java spring事务管理系统_Spring 编程事物管理-程序员宅基地

技术标签: java 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

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_42133918/article/details/114207527

智能推荐

访问类私有成员(非友元函数, 非成员函数)-程序员宅基地

文章浏览阅读258次。为什么80%的码农都做不了架构师?>>> ..._非友元非成员函数怎么访问类内成员

代码报错原因和处理方法-程序员宅基地

文章浏览阅读8.5k次。代码错误的原因和调试方法_代码报错

单片机与ARM嵌入式区别_arm嵌入式和单片机的区别-程序员宅基地

文章浏览阅读514次。本文主要针对ARM公司不同架构的芯片区别Cortex系列属于ARMv7架构,这是到2010年为止ARM公司最新的指令集架构。(2011年,ARMv8 架构在 TechCon 上推出)ARMv7架构定义了三大分工明确的系列:“A”系列面向尖端的基于虚拟内存的操作系统和用户应用;“R”系列针对实时系统;“M”系列对微控制器。图中的ARM7,ARM9,ARM11是ARM公司未更名前的芯片命名规则,其中ARM7属于低端处理器,ARM9,ARM11为中高端处理器。目前差用的STM32为Cortex-_arm嵌入式和单片机的区别

macos 10.13安装python3_macos10.13应该下载哪个版本的python-程序员宅基地

文章浏览阅读1.5k次。http://www.cnblogs.com/i-am-lvjiazhen/p/6264354.html_macos10.13应该下载哪个版本的python

浏览器前端页面连接wss,提示ERR_CERT_AUTHORITY_INVALID_wss 连接 err_cert_authority_invalid-程序员宅基地

文章浏览阅读7.1k次。浏览器提示原文:WebSocket connection to ‘wss://192.1681.100:8443/ws’ failed: Error in connection establishment: net::ERR_CERT_AUTHORITY_INVALID错误原因:使用加密的WebSocket时,需要配置证书,以下几点需要注意:WebSocket地址不能使用IP,必须使用域名。因为证书是针对域名来进行配置的。证书必须符合新Chrome规范,否则会出现NET::ERR_CERT_CO_wss 连接 err_cert_authority_invalid

关于Mybatis中的properties属性&&标签中url和resource属性的使用_property name="username"什么意思-程序员宅基地

文章浏览阅读5k次,点赞4次,收藏6次。我们使用Mybatis的时候是需要在配置文件中配置property属性的最直接的写法最简单的写法就是直接将全部内容写在dataSource标签下,即<dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatisstudy_property name="username"什么意思

随便推点

通信原理第五、六章_将基带信号转换成极性码,映射-程序员宅基地

文章浏览阅读1.8k次。写在前面:黄色部分,p是书上有公式的要动手写的部分及对应页码文章目录第五章:基带传输系统第六章二进制:M进制:第五章:基带传输系统:波形变换–>信道–>接受滤波器–>抽样判决数字基带信号:短距离有线传输,频谱范围WB 从直流或低频延伸至若干倍1/T数字载波调制信号:无线,光纤信道,经过调制实现信号频谱搬移基带信号码型的设计原则:1.不含直流分量2.高频分量少..._将基带信号转换成极性码,映射

疱疹性结膜炎_带状疱疹经历的四个阶段 知乎-程序员宅基地

文章浏览阅读404次。疱疹性结膜炎特征为角膜上皮呈树枝状病变,与树叶的叶脉相似,末端呈球形.早期症状为异物感,流泪,畏光和结膜充血,随着反复复发,角膜知觉减退或消失,结果可能引起角膜溃疡和永久性角膜瘢痕形成. 盘状角膜炎累及角膜基质,是角膜深层的盘状局限性水肿和混浊,伴有虹膜炎,常在上皮性角膜炎后发生.盘状角膜炎可能代表机体对病毒的免疫反应.不是由反复的单纯疱疹病毒引起的不愈合或愈合极慢的上皮性缺损,被称为无痛性溃疡._带状疱疹经历的四个阶段 知乎

Sybase杂记(一)_sybase union all并排序-程序员宅基地

文章浏览阅读1.2k次。 现在网上搜索关于数据库的优化文章都是基于Oracle和MSSQL这两种数据库,而专门针对Sybase数据库却寥寥无几。虽然MSSQL和Sybase有很多相似的地方(因为两者有一定的历史渊源,我就不在这里讲了,有兴趣的可以去google上搜索):如他们都支持T-SQL(T-SQL需要帮助时,我首先会用MSSQL的帮助系统。在这里不得不说一句微软的技术支持做的是比Sybase好很多,sybase官_sybase union all并排序

第十三篇:Linux常见命令_linux pid nid-程序员宅基地

文章浏览阅读211次。1. 如果系统突然变慢如何排查?2. CPU突然被打满了如何解决?_linux pid nid

Java 语法基础总结_java基本语法实验总结-程序员宅基地

文章浏览阅读655次。Java 语法基础1.常量和变量量是用来传递数据的介质,有着十分重要的作用。Java语言中的量既可以是变化的,也可以是固定不变的。根据是否可变,可以将Java中的量分为变量和常量。1.1.常量永远不变的量就是常量,常量的值不会随着时间的变化而发生改变,在程序中通常用来表示某一固定值的字符或字符串。在Java程序中,我们经常会用大写字母来表示常量名,使用final关键字来定义常量,具体格式如下:final double PI=3.1415926;1.2.变量在Java程序中,变量是指在程序运行_java基本语法实验总结

Go语言学习笔记(十九)_golang ifconfig-程序员宅基地

文章浏览阅读175次。超文本传输协议(Hypertext Transfer Protocol, HTTP)是一种在互联网上收发资源的网络协议,用于传输图像、HTML文档和JSON等。本章介绍如何使用Go语言创建HTTP客户端,你将学习如何发出各种类型的请求,还有如何在开发期间调试程序。_golang ifconfig