事务:保证数据的运行不会说A给B钱,A钱给了B却没收到。

实现事务的三种方式(重要代码):

1.aspectJ AOP实现事务:

<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dateSource"></property>
</bean>
<tx:advice id="stockAdvice" transaction-manager="dataSourceTransactionManager">
<tx:attributes>
<tx:method name="by*" isolation="DEFAULT" propagation="REQUIRED" rollback-for="MyExepction"/>
<tx:method name="select*" isolation="DEFAULT" propagation="REQUIRED" read-only="true"></tx:method>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="exAdvice" expression="execution(* *..service.*.*(..))"></aop:pointcut>
<aop:advisor advice-ref="stockAdvice" pointcut-ref="exAdvice"></aop:advisor>
</aop:config>

2.事务代理工厂Bean实现事务:

<bean id="tproxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager" ref="dataSourceTransactionManager"></property>&lt;!&ndash;写的是事务&ndash;&gt;
<property name="target" ref="byStockService"></property>&lt;!&ndash;要进行事务的类&ndash;&gt;
<property name="transactionAttributes">
<props>&lt;!&ndash;key写的是service层要增强的方法&ndash;&gt;
&lt;!&ndash; 事务的隔离级别,后面逗号后面是异常类,用于回滚数据&ndash;&gt;
<prop key="ByStock">ISOLATION_DEFAULT,PROPAGATION_REQUIRED,-MyExepction</prop>
</props>
</property>
</bean>

3.注解方式实现事务:

<tx:annotation-driven transaction-manager="dataSourceTransactionManager"/>
在需要进行事务的方法上增加一个注解“@Transactional(rollbackFor = MyExepction.class )”

做一个买股票的小例子来看一下事务:

1.使用事务工厂Bean:

xml:

这个异常刚好卡在支付金额,和股票增加直接,

 RuntimeException是运行时异常
Exception是检查异常
两者的区别:
运行时异常是默认回滚,
检查异常是默认提交的。

数据表:

结果异常出现后,数据进行了回滚,A表中并没有少余额,B表中也没有多股票。

基本的架构:

  dao:

IStockDao:
package cn.Spring.Day20xy.dao;

public interface IStockDao {
public int updateStock(int sid,int soucnt,boolean isbuay)throws Exception;
}
IAccountDao:
package cn.Spring.Day20xy.dao;

public interface IAccountDao {
public int updateAccount(int aid,Double amoeny,boolean isbay) throws Exception;
}
StockDaoImpl:
package cn.Spring.Day20xy.dao;

import org.springframework.jdbc.core.support.JdbcDaoSupport;

public class StockDaoImpl extends JdbcDaoSupport implements IStockDao {

    @Override
public int updateStock(int sid, int soucnt, boolean isbuay) throws Exception {
String sql="";
if (isbuay){
sql="update stock set scount=scount+? where sid=?";
}else {
sql="update stock set scount=scount-? where sid=?";
}
return this.getJdbcTemplate().update(sql,soucnt,sid);
}
}
AccountDaoImpl:
package cn.Spring.Day20xy.dao;

import org.springframework.jdbc.core.support.JdbcDaoSupport;

public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao{
@Override
public int updateAccount(int aid,Double amoeny,boolean isbay) throws Exception {
String sql="";
if (isbay){
sql="update account set abalance=abalance-? where aid=?";
}else {
sql="update account set abalance=abalance+? where aid=?";
}
return this.getJdbcTemplate().update(sql,amoeny,aid);
}
}

  entity:

Account:
package cn.Spring.Day20xy.entity;

public class Account {
private Integer aid;
private String aname;
private double abalance; public Integer getAid() {
return aid;
} public void setAid(Integer aid) {
this.aid = aid;
} public String getAname() {
return aname;
} public void setAname(String aname) {
this.aname = aname;
} public double getAbalance() {
return abalance;
} public void setAbalance(double abalance) {
this.abalance = abalance;
}
}

  

Stock:
package cn.Spring.Day20xy.entity;

public class Stock {
//股票代号
private Integer sid; //股票名称
private String sname; //股数
private Integer scount; public Integer getSid() {
return sid;
} public void setSid(Integer sid) {
this.sid = sid;
} public String getSname() {
return sname;
} public void setSname(String sname) {
this.sname = sname;
} public Integer getScount() {
return scount;
} public void setScount(Integer scount) {
this.scount = scount;
}
}
MyExepction:
package cn.Spring.Day20xy.entity;

public class MyExepction extends RuntimeException {
public MyExepction() {
} public MyExepction(String message) {
super(message);
} }

  service:

IByStockService :

package cn.Spring.Day20xy.service;

public interface IByStockService {
public int ByStock(int aid,double moeny,int sid ,int count)throws Exception;
}
ByStockServiceImpl:
package cn.Spring.Day20xy.service;

import cn.Spring.Day20xy.dao.IAccountDao;
import cn.Spring.Day20xy.dao.IStockDao;
import cn.Spring.Day20xy.entity.MyExepction;
import org.springframework.transaction.annotation.Transactional; public class ByStockServiceImpl implements IByStockService{
//植入Dao
private IAccountDao accountDao;
private IStockDao stockDao; @Override
@Transactional(rollbackFor = MyExepction.class )
public int ByStock(int aid,double moeny,int sid ,int count) throws Exception {
boolean isbay=true;
int i = accountDao.updateAccount(aid, moeny, isbay);
if (1==1) {
throw new MyExepction("出异常了");
}
int i1 = stockDao.updateStock(sid, count, isbay);
return i+i1;
} public IAccountDao getAccountDao() {
return accountDao;
} public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
} public IStockDao getStockDao() {
return stockDao;
} public void setStockDao(IStockDao stockDao) {
this.stockDao = stockDao;
}
}

  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"
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.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--1.配置数据源-->
<bean id="dateSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql:///newss2230"></property>
<property name="username" value="root"></property>
<property name="password" value="123"></property>
</bean>
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<!--2.JDBCTampLate-->
<bean id="jdbcTempLate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dateSource"></property>
</bean>
<!--3.Dao-->
<bean id="accountDao" class="cn.Spring.Day20xy.dao.AccountDaoImpl">
<property name="jdbcTemplate" ref="jdbcTempLate"></property>
</bean>
<!--3.Dao-->
<bean id="stockDao" class="cn.Spring.Day20xy.dao.StockDaoImpl">
<property name="jdbcTemplate" ref="jdbcTempLate"></property>
</bean>
<!--4.Service-->
<bean id="byStockService" class="cn.Spring.Day20xy.service.ByStockServiceImpl">
<property name="accountDao" ref="accountDao"></property>
<property name="stockDao" ref="stockDao"></property> <!--事务-->
</bean>
<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dateSource"></property>
</bean> <!--事务注解驱动-->
<tx:annotation-driven transaction-manager="dataSourceTransactionManager"/>
<!--事务代理工厂bean-->
<!--<bean id="tproxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager" ref="dataSourceTransactionManager"></property>
<property name="target" ref="byStockService"></property>
<property name="transactionAttributes">
<props>&lt;!&ndash;key写的是service层的方法&ndash;&gt;
<prop key="ByStock">ISOLATION_DEFAULT,PROPAGATION_REQUIRED,-MyExepction</prop>
</props>
</property>
</bean>-->
</beans>

Spring 实现事务的三种方式的更多相关文章

  1. spring生成EntityManagerFactory的三种方式

    spring生成EntityManagerFactory的三种方式 1.LocalEntityManagerFactoryBean只是简单环境中使用.它使用JPA PersistenceProvide ...

  2. Spring 使用AspectJ的三种方式

    Spring 使用AspectJ 的三种方式 一,使用JavaConfig 二,使用注解隐式配置 三,使用XML 配置 背景知识: 注意 使用AspectJ 的 时候 要导入相应的Jar 包 嗯 昨天 ...

  3. spring创建bean的三种方式

    spring创建bean的三种方式: 1通过构造方法创建bean(最常用) 1.1 spring默认会通过无参构造方法来创建bean,如果xml文件是这样配置,则实体类中必须要有无参构造方法,无参构造 ...

  4. Spring静态注入的三种方式

    版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/chen1403876161/article/details/53644024Spring静态注入的三 ...

  5. Spring 循环依赖的三种方式(三级缓存解决Set循环依赖问题)

    本篇文章解决以下问题: [1] . Spring循环依赖指的是什么? [2] . Spring能解决哪种情况的循环依赖?不能解决哪种情况? [3] . Spring能解决的循环依赖原理(三级缓存) 一 ...

  6. SSH深度历险记(八) 剖析SSH核心原则+Spring依赖注入的三种方式

           于java发育.一类程序猿必须依靠类的其他方法,它是通常new依赖类的方法,然后调用类的实例,这样的发展问题new良好的班统一管理的例子.spring提出了依赖注入的思想,即依赖类不由程 ...

  7. SSH深度历险(八) 剖析SSH核心原理+Spring依赖注入的三种方式

           在java开发中,程序员在某个类中需要依赖其它类的方法,则通常是new一个依赖类再调用类实例的方法,这种开发存在的问题是new的类实例不好统一管理,spring提出了依赖注入的思想,即依 ...

  8. Spring配置dataSource的三种方式 数据库连接池

    1.使用org.springframework.jdbc.dataSource.DriverManagerDataSource 说明:DriverManagerDataSource建立连接是只要有连接 ...

  9. spring mvc handler的三种方式

    springmvc.xml 三种方式不能针对一个controller同时使用 <?xml version="1.0" encoding="UTF-8"?& ...

随机推荐

  1. openstack系列文章(2)dashboard

    玩转dashboard之前,考虑一些事情:(1)安全问题:网络访问策略(2)镜像的密码管理:windows或者linux,root或者administrator密码怎么管理(3)怎样创建自己的镜像:w ...

  2. vue项目部署到服务器

    1.配置config目录下index.js index: path.resolve(__dirname, '../dist/index.html'), assetsRoot: path.resolve ...

  3. p2p技术之n2n源码核心简单分析一

    首先在开篇之前介绍下内网打洞原理 场景:一个服务器S1在公网上有一个IP,两个私网机器C1,C2 C1,C2分别由NAT1和NAT2连接到公网,我们需要借助S1将C1,C2建立直接的TCP连接,即由C ...

  4. 让粒子可以在白色背景显示 [Blending Shader 实操]

    Unity3D 提供了粒子特效的各种shader,今天要说的是 Additive(因为项目最初就是用了Additive 发生了问题.. ε=ε=ε=┏(゜ロ゜;)┛) Additive Particl ...

  5. ajax 参数记录

    1.url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址. 2.type: 要求为String类型的参数,请求方式(post或get)默认为get.注意其他http请求方法,例如 ...

  6. LOL新版符文 怎么查看队友的符文配置?

    LOL怎么看其他玩家符文? 像我这种名字都懒的打的, 直接去WeGame复制昵称. 然后在LOL主界面点生涯, 之后搜索 光头强xian生

  7. 解决Xcode8模拟器无法删除应用的问题

    关闭模拟器的​3DTouch.Hardware​ →Touch Pressure→Use Trackpad Force.

  8. [少数派]如何学习Git

    用玩游戏的方式学习 Git 目录 为什么要学习 Git 怎么学习 Git Learn Git Branching 其他学习资源 用游戏的方式来学习,是一种有趣而高效的方式. 从刚接触电脑时的打字练习软 ...

  9. 初入pygame——贪吃蛇

    一.问题利用pygame进行游戏的编写,做一些简单的游戏比如贪吃蛇,连连看等,后期做完会把代码托管. 二.解决 1.环境配置 python提供一个pygame的库来进行游戏的编写.首先是安装pygam ...

  10. 阿里云 ECS centos java timer进程异常/混乱......的解决方法

    之前就知道timer进程长久运行容易出问题,所以一直对timer进行了很长一段时间的日志监控和数据库记录,大概观察了几个月,没发现过问题....然后就没管理了,数据库记录也没做了,昨天这问题就来了,t ...