Java进阶知识24 Spring的事务管理(事务回滚)
1、事务控制概述
1.1、编程式事务控制
自己手动控制事务,就叫做编程式事务控制。
Jdbc代码: connection.setAutoCommit(false); // 设置手动控制事务
Hibernate代码: session.beginTransaction(); // 开启一个事务
transaction.rollback(); //事务回滚
【细粒度的事务控制: 可以对指定的方法、指定的方法的某几行添加事务控制】 (比较灵活,但开发起来比较繁琐: 每次都要开启、提交、回滚.)
1.2、Spring声明式事务控制
Spring提供了对事务的管理,这个就叫做声明式事务管理。
Spring提供了对事务控制的实现。用户如果想用Spring的声明式事务管理,只需要在配置文件中配置即可; 不想使用时直接移除配置。这个实现了对事务控制的最大程度的解耦。
Spring声明式事务管理,核心实现就是基于Aop。
【粗粒度的事务控制: 只能给整个方法应用事务,不可以对方法的某几行应用事务。】(因为aop拦截的是方法。)
2、Spring声明式事务管理器类
Jdbc技术:DataSourceTransactionManager
Hibernate技术:HibernateTransactionManager
2.1、JDBC技术
<!-- ############Spring声明式事务管理配置########### -->
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean> <!-- 配置事务增强(针对DAO层) -->
<tx:advice transaction-manager="transactionManager" id="transactionAdvice">
<tx:attributes> <!-- *代表dao层的所有方法 -->
<tx:method name="*" read-only="false"/>
</tx:attributes>
</tx:advice> <!-- AOP配置:配置切入点表达式 -->
<aop:config>
<aop:pointcut expression="execution(* com.shore.service.impl.UserService.save(..))" id="pt"/>
<aop:advisor advice-ref="transactionAdvice" pointcut-ref="pt"/>
</aop:config>
说明:上面代码是在Spring 配置文件(beans.xml)里面的,只要DAO层或Service层某个方法出现异常,都会引起“事务回滚”,即:该异常方法对数据库表的CRUD操作都会撤销回来。如果不要这个Spring事务管理,删除即可,不会对其他代码产生影响的;这段代码的主要用作就是:当DAO层或Service层某个方法出现异常时,进行事务回滚。
2.2、Hibernate技术
<!-- ############Spring声明式事务管理配置########### -->
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean> <!-- 配置事务增强(针对DAO层) -->
<tx:advice transaction-manager="transactionManager" id="transactionAdvice">
<tx:attributes> <!-- *代表DAO层的所有方法 -->
<tx:method name="*" read-only="false"/>
</tx:attributes>
</tx:advice> <!-- AOP配置:配置切入点表达式 -->
<aop:config> <!-- 第一个*表示返回值类型;第二个*表示service层下的所有接口实现类;第三个*表示每个接口实现类下的所有方法 -->
<aop:pointcut expression="execution(* com.shore.service.impl.*.*(..))" id="pt"/>
<aop:advisor advice-ref="transactionAdvice" pointcut-ref="pt"/>
</aop:config>
说明:和JDBC技术的一样,只有“配置事务管理器”处的代码不一样。
附录
1、Spring+JDBC 版本:
接口实现类(UserDao)
public class UserDao implements IUserDao{
private JdbcTemplate jdbcTemplate; //这里与Spring的配置文件 DAO层 对接 public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
} @Override
public void save(User user) {
jdbcTemplate.update("insert into user(name) values(?)",user.getName(),user.getAge());
}
}
我测试用到的完整Spring配置文件(beans.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: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.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- c3p0数据库连接池配置 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring_0301_transaction"></property>
<property name="user" value="root"></property>
<property name="password" value="zhaoyong"></property>
<property name="initialPoolSize" value="3"></property>
<property name="maxPoolSize" value="100"></property>
<property name="maxStatements" value="200"></property>
<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
<property name="acquireIncrement" value="2"></property>
</bean> <!-- JDBCTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property> <!-- 这里和下面的“配置事务管理器”处对接 -->
</bean> <!-- Dao层 -->
<bean id="userDao" class="com.shore.dao.impl.UserDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean> <!-- Service层 -->
<bean id="userService" class="com.shore.service.impl.UserService">
<property name="userDao" ref="userDao"></property>
</bean> <!-- Action层 -->
<bean id="userAction" class="com.shore.action.UserAction">
<property name="userService" ref="userService"></property>
</bean> <!-- ############Spring声明式事务管理配置########### -->
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean> <!-- 配置事务增强(针对DAO层) -->
<tx:advice transaction-manager="transactionManager" id="transactionAdvice">
<tx:attributes> <!-- *代表DAO层的所有方法 -->
<tx:method name="*" read-only="false"/>
</tx:attributes>
</tx:advice> <!-- AOP配置:配置切入点表达式 -->
<aop:config>
<aop:pointcut expression="execution(* com.shore.service.impl.UserService.save(..))" id="pt"/>
<aop:advisor advice-ref="transactionAdvice" pointcut-ref="pt"/>
</aop:config>
</beans>
2、Spring+Hibernate 版本:
接口实现类(UserDao)
public class UserDao implements IUserDao{
//从IoC容器注入SessionFactory
private SessionFactory sessionFactory; //这里与Spring的配置文件 DAO层 对接
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
} @Override
public void save(User user) {
sessionFactory.getCurrentSession().save(user);
}
}
我测试用到的完整Spring配置文件(beans.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: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.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- Spring去读取Hibernate配置文件(hibernate.cfg.xml) -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
</bean> <bean id="userDao" class="com.shore.dao.impl.UserDao">
<property name="sessionFactory" ref="sessionFactory"></property> <!-- 这里和下面的“配置事务管理器”处对接 -->
</bean> <bean id="userService" class="com.shore.service.impl.UserService">
<property name="userDao" ref="userDao"></property>
</bean>
<bean id="userAction" class="com.shore.action.UserAction">
<property name="userService" ref="userService"></property>
</bean>
<!-- ############Spring声明式事务管理配置########### -->
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean> <!-- 配置事务增强(针对DAO层) -->
<tx:advice transaction-manager="transactionManager" id="transactionAdvice">
<tx:attributes> <!-- *代表DAO层的所有方法 -->
<tx:method name="*" read-only="false"/>
</tx:attributes>
</tx:advice> <!-- AOP配置:配置切入点表达式 -->
<aop:config> <!-- 第一个*表示返回值类型;第二个*表示service层下的所有接口实现类;第三个*表示每个接口实现类下的所有方法 -->
<aop:pointcut expression="execution(* com.shore.service.impl.*.*(..))" id="pt"/>
<aop:advisor advice-ref="transactionAdvice" pointcut-ref="pt"/>
</aop:config>
</beans>
我测试用到的完整Hibernate配置文件(hibernate.cfg.xml)
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/spring_hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">123456</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update</property> <mapping resource="com/shore/entity/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
实体类(User)的Hibernate配置文件(User.hbm.xml)
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.shore.entity">
<class name="User">
<id name="id">
<generator class="native"/>
</id>
<property name="name" type="java.lang.String"/>
<property name="age" type="java.lang.Integer"/>
</class>
</hibernate-mapping>
原创作者:DSHORE 作者主页:http://www.cnblogs.com/dshore123/ 原文出自:https://www.cnblogs.com/dshore123/p/11830488.html 欢迎转载,转载务必说明出处。(如果本文对您有帮助,可以点击一下右下角的 推荐,或评论,谢谢!) |
Normal
0
7.8 磅
0
2
false
false
false
EN-US
ZH-CN
X-NONE
/* Style Definitions */
table.MsoNormalTable
{mso-style-name:普通表格;
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-priority:99;
mso-style-qformat:yes;
mso-style-parent:"";
mso-padding-alt:0cm 5.4pt 0cm 5.4pt;
mso-para-margin:0cm;
mso-para-margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:10.5pt;
mso-bidi-font-size:11.0pt;
font-family:"Calibri","sans-serif";
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-bidi-font-family:"Times New Roman";
mso-bidi-theme-font:minor-bidi;
mso-font-kerning:1.0pt;}
Java进阶知识24 Spring的事务管理(事务回滚)的更多相关文章
- Java进阶知识25 Spring与Hibernate整合到一起
1.概述 1.1.Spring与Hibernate整合关键点 1) Hibernate的SessionFactory对象交给Spring创建. 2) hibernate事务交给spring的声明 ...
- 【Java EE 学习 54】【OA项目第一天】【SSH事务管理不能回滚问题解决】【struts2流程回顾】
一.SSH整合之后事务问题和总结 1.引入问题:DAO层测试 假设将User对象设置为懒加载模式,在dao层使用load方法. 注意,注释不要放开. 使用如下的代码块进行测试: 会报错:no sess ...
- Spring事务管理----事物回滚
Spring的事务管理默认只对未检查异常(java.lang.RuntimeException及其子类)进行回滚,如果一个方法抛出Checked异常,Spring事务管理默认不进行回滚. 改变默认方式 ...
- Java进阶知识20 Spring的代理模式
本文知识点(目录): 1.概念 2.代理模式 2.1.静态代理 2.2.动态代理 2.3.Cglib子类代理 1.概念 1.工厂模式 2. 单例模式 代理(Proxy ...
- Java进阶知识15 Spring的基础配置详解
1.SSH各个的职责 Struts2:是web框架(管理jsp.action.actionform等).Hibernate:是ORM框架,处于持久层.Spring:是一个容器框架,用于配置bean,并 ...
- Java进阶知识23 Spring对JDBC的支持
1.最主要的代码 Spring 配置文件(beans.xml) <!-- 连接池 --> <bean id="dataSource" class="co ...
- Java进阶知识22 Spring execution 切入点表达式
1.概述 切入点(execution ):可以对指定的方法进行拦截,从而给指定的类生成代理对象.(拦截谁,就是在谁那里切入指定的程序/方法) 格式: execution(modifiers-pat ...
- Java进阶知识21 Spring的AOP编程
1.概述 Aop:(Aspect Oriented Programming)面向切面编程 功能: 让关注点代码与业务代码分离! 关注点:重复代码就叫做关注点:切面: 关注点形成的类, ...
- Java进阶知识17 Spring Bean对象的创建细节和创建方式
本文知识点(目录): 1.创建细节 1) 对象创建: 单例/多例 2) 什么时候创建? 3)是否延迟创建(懒加载) 4) 创建对象之后, ...
随机推荐
- C# 关于爬取网站数据遇到csrf-token的分析与解决
需求 某航空公司物流单信息查询,是一个post请求.通过后台模拟POST HTTP请求发现无法获取页面数据,通过查看航空公司网站后,发现网站使用避免CSRF攻击机制,直接发挥40X错误. 关于CSRF ...
- 【shell脚本】$ 在shell脚本中的使用
shell脚本中 '$' 与不同的符号搭配其表示的意义也会不同 特殊标志符 含义 $0 当前脚本的文件名 $n 传递给脚本或函数的参数.n 是一个数字,表示第几个参数. 例如,第一个参数是$1,第二个 ...
- spingboot启动报驱动Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of th
原因: springboot应用了最新的驱动com.mysql.cj.jdbc.Driver,这个驱动需要用mysql-connector-java包的6.x版本才可以, 而mysql-connect ...
- DOM树节点关系
DOM是JS中专门操作HTML页面内容的 他的三种基本使用方法是: 1. document.getElementById(''): ——>选取html页面中带有Id的属性名: 2.docum ...
- S2-019、S2-020
前言 “Struts2系列起始篇”是我整各系列的核心,希望大家能花些时间先看看. 正文 我发现关于一些早期的Struts2的漏洞,网上的分析文章并不多,不知道是不是我打开浏览器的方式不对,唯一看到的两 ...
- JS Array.reverse 将数组元素颠倒顺序
<pre><script type="text/javascript"> //JS Array.reverse 将数组元素颠倒顺序//在JavaScript ...
- 《构建之法》——Alpha2项目的测试
这个作业属于哪个课程 课程的链接 这个作业要求在哪里 作业要求的链接 团队名称 Runningman 这个作业的目标 测试其他组的项目,互相借鉴 作业正文 作业正文 测试人姓名 陈嘉莹 测试人学号 2 ...
- Wireless Network(并查集)
POJ - 2236 #include<iostream> #include<algorithm> #include<cstring> #include<cm ...
- 字符串搜索(strStr)--- java版
这里来学习一下从一个源字符串中搜索指定的字符串,有些啰嗦,直接看最终的效果: 实际上JAVA SDK中相当于String.indexOf()方法,上面的用例改用JAVA SDK来实现看一下: 编译运行 ...
- Python 常用的ORM框架简介
ORM概念ORM(Object Ralational Mapping,对象关系映射)用来把对象模型表示的对象映射到基于S Q L 的关系模型数据库结构中去.这样,我们在具体的操作实体对象的时候,就不需 ...