一、传统事务

二、通过spring配置完成事务:

1、配置spring,加入spring的jar包,加入spring的配置文件

2、配置数据源,这里使用c3p0,加入c3p0 jar包和mysql数据库驱动包,配置

<context:property-placeholder location="classpath:db.properties" />
<!-- 配置数据源 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property> <property name="initialPoolSize" value="${jdbc.initialPoolSize}"></property>
<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
</bean>

3、配置spring jdbcTemplate

<!-- 配置jdbcTemplate -->
<bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>

4、配置事务管理器和spring注解事务

<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>

完整的配置文件:

<?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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> <context:property-placeholder location="classpath:db.properties" />
<context:component-scan base-package="com.hy"></context:component-scan>
<!-- 配置数据源 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property> <property name="initialPoolSize" value="${jdbc.initialPoolSize}"></property>
<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
</bean> <!-- 配置jdbcTemplate -->
<bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean> <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

三、编写一个测试实例:

这里使用简单三表演示,用户、图书、库存三表

package com.hy;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import com.hy.dao.BookShopDao;
import com.hy.service.BookShopService; public class TestSpringTransaction { private ApplicationContext app; private BookShopDao bookShopDao; private BookShopService bookShopService; {
app = new ClassPathXmlApplicationContext("applicationContext.xml");
bookShopDao = app.getBean(BookShopDao.class);
bookShopService = app.getBean(BookShopService.class);
} @Test
public void testFindPriceByIsbn() {
System.out.println(bookShopDao.findBookPriceByIsbn("1001"));
} @Test
public void testUpdateStock() {
bookShopDao.updateBookStock("1001");
} @Test
public void testUpdateAccount() {
bookShopDao.updateUserAccount("AA", 100);
} @Test
public void testPurchase() {
bookShopService.purchaseBook("AA", "1001");
} }

此处使用了注解执行事务:

dao注解:

package com.hy.dao;

import java.net.SocketException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository; import com.hy.exception.AccountException;
import com.hy.exception.StockException; @Repository("bookShopDao")
public class BookShopDaoImpl implements BookShopDao { @Autowired
private JdbcTemplate jdbcTemplate; @Override
public int findBookPriceByIsbn(String isbn) {
String sql = "select price from book where isbn = ?";
return jdbcTemplate.queryForObject(sql, Integer.class, isbn);
} @Override
public void updateBookStock(String isbn) {
String sql2 = "select stock from book_stock where isbn = ?";
int stock = jdbcTemplate.queryForObject(sql2, Integer.class, isbn);
if (stock == 0) {
throw new StockException("库存不足");
} String sql = "update book_stock set stock = stock - 1 where isbn = ?";
jdbcTemplate.update(sql, isbn);
} @Override
public void updateUserAccount(String username, int price) {
String sql2 = "select balance from account where username = ?";
int balance = jdbcTemplate.queryForObject(sql2, Integer.class, username);
if (balance < price) {
throw new AccountException("余额不足");
} String sql = "update account set balance = balance - ? where username = ?";
jdbcTemplate.update(sql, price, username); } }

service注解:

package com.hy.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import com.hy.dao.BookShopDao; @Service("bookShopService")
public class BookShopServiceImpl implements BookShopService { @Autowired
private BookShopDao bookShopDao; @Transactional
@Override
public void purchaseBook(String username, String isbn) {
int price = bookShopDao.findBookPriceByIsbn(isbn);
bookShopDao.updateBookStock(isbn);
bookShopDao.updateUserAccount(username, price);
} }

包扫描配置:

<context:component-scan base-package="com.hy"></context:component-scan>

附录:源代码链接:

http://pan.baidu.com/s/1cJzTLk

spring声明式事务的更多相关文章

  1. spring声明式事务管理总结

    事务配置 首先在/WEB-INF/applicationContext.xml添加以下内容: <!-- 配置事务管理器 --> <bean id="transactionM ...

  2. spring 声明式事务管理

    简单理解事务: 比如你去ATM机取5000块钱,大体有两个步骤:首先输入密码金额,银行卡扣掉5000元钱:然后ATM出5000元钱.这两个步骤必须是要么都执行要么都不执行.如果银行卡扣除了5000块但 ...

  3. Spring声明式事务管理基于@Transactional注解

    概述:我们已知道Spring声明式事务管理有两种常用的方式,一种是基于tx/aop命名空间的xml配置文件,另一种则是基于@Transactional 注解.         第一种方式我已在上文为大 ...

  4. Spring声明式事务管理基于tx/aop命名空间

    目的:通过Spring AOP 实现Spring声明式事务管理; Spring支持编程式事务管理和声明式事务管理两种方式. 而声明式事务管理也有两种常用的方式,一种是基于tx/aop命名空间的xml配 ...

  5. Spring声明式事务配置管理方法

    环境配置 项目使用SSH架构,现在要添加Spring事务管理功能,针对当前环境,只需要添加Spring 2.0 AOP类库即可.添加方法: 点击项目右键->Build Path->Add ...

  6. 161117、使用spring声明式事务抛出 identifier of an instance of

    今天项目组有成员使用spring声明式事务出现下面异常,这里跟大家分享学习下. 异常信息: org.springframework.orm.hibernate3.HibernateSystemExce ...

  7. Spring声明式事务管理与配置详解

    转载:http://www.cnblogs.com/hellojava/archive/2012/11/21/2780694.html 1.Spring声明式事务配置的五种方式 前段时间对Spring ...

  8. Spring声明式事务配置管理方法(转)

    项目使用SSH架构,现在要添加Spring事务管理功能,针对当前环境,只需要添加Spring 2.0 AOP类库即可.添加方法: 点击项目右键->Build Path->Add libra ...

  9. Spring声明式事务的配置~~~

    /*2011年8月28日 10:03:30 by Rush  */ 环境配置 项目使用SSH架构,现在要添加Spring事务管理功能,针对当前环境,只需要添加Spring 2.0 AOP类库即可.添加 ...

  10. Spring 声明式事务,propagation属性列表及isolation(隔离级别)

    Spring 声明式事务,propagation属性列表 TransactionDefinition接口中定义,共有7种选项可用: PROPAGATION_REQUIRED:支持当前事务,如果当前没有 ...

随机推荐

  1. SQLServer中临时表与表变量的区别分析

    临时表 临时表与永久表相似,只是它的创建是在Tempdb中,它只有在一个数据库连接结束后或者由SQL命令DROP掉,才会消失,否则就会一直存在.临时表在创建的时候都会产生SQL Server的系统日志 ...

  2. prtg

    prtg http://www.paessler.com/prtg/features prtg的sensor技术 数据库监视 Flexible Alerting 9 notification tech ...

  3. 【转】c# winform 打包部署 自定义界面 或设置开机启动

    方法一: 创建安装部署这部分就不用说了,添加安装部署项目后,鼠标右键安装项目->视图->注册表, 要使软件在开机就运行,可以在HKEY_CURRENT_USER\Software\Micr ...

  4. Android-Adapter用法总结

    1.概念 Adapter是连接后端数据和前端显示的适配器接口,是数据和UI(View)之间一个重要的纽带.在常见的 View(ListView,GridView)等地方都需要用到Adapter.如下图 ...

  5. python escape sequences

    转义字符 描述 \(在行尾时) 续行符 \\ 反斜杠符号 \' 单引号 \" 双引号 \a 响铃 \b 退格(Backspace) \e 转义 \000 空 \n 换行 \v 纵向制表符 \ ...

  6. 导入安卓项目的时候,发生错误:Cause: peer not authenticated

    导入安卓项目时出现Cause: peer not authenticated. 在网上搜了解决方案,都没有凑效.后来干脆插上手机直接debug安装,竟然成功了,成功了,成功了!!!! 然后再次buil ...

  7. web首页设置如下代码可判断用户是用什么设备登录的?

    var OnePage=true;//用来判断staticHtml.js中首页登入的信息判断var _mobileUrl = "http://a.abc.com";//手机用户通过 ...

  8. DW(六):polybase访问Azure Blob Storage

    目录: 连接hadoop配置语法 配置hadoop连接 Pushdown配置 Create external tables for Azure blob storage 连接hadoop配置语法: g ...

  9. HTML5跨浏览器表单及HTML5表单的渐进增强

    HTML5跨浏览器表单 http://net.tutsplus.com/tutorials/html-css-techniques/how-to-build-cross-browser-html5-f ...

  10. Hibernate延迟加载机制详解

    摘自 http://blog.chinaunix.net/uid-20577907-id-3129234.html 1 延迟加载: 延迟加载机制是为了避免一些无谓的性能开销而提出来的,所谓延迟加载就是 ...