ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Spring学习-6-Spring事务管理

2020-12-13 12:01:56  阅读:194  来源: 互联网

标签:事务管理 事务 Spring update 接口 学习 balance


Spring事务

        在实际开发中,操作数据库时都会涉及到事务管理问题,为此Spring提供了专门用于事务处理的API。 Spring的事务管理简化了传统的事务管理流程,并且在一定程度上减少了开发者的工作量。


事务管理的核心接口

 1.Platform TransactionManager

PlatformTransactionManager接口是Spring提供的平台事务管理器,主要用于管理事务。该接口中提供了三个事务操作的方法,具体如下:
            TransactionStatus getTransaction(TransactionDefinition definition); 用于获取事务状态信息
            void commit(TransactionStatus status);  用于提交事务
            void rollback(TransactionStatus status);  用于回滚事务


PlatformTransactionManager接口只是代表事务管理的接口,并不知道底层是如何管理事务的,具体如何管理事务则由它的实现类来完成。该接口常见的几个实现类如下:                             

        org.springframework.jdbc.datasource.DataSourceTransactionManager   用于配置JDBC数据源的事务管理器        
        org.springframework.orm.hibernate4.HibernateTransactionManager        用于配置Hibernate的事务管理器
        org.springframework.transaction.jta.JtaTransactionManager                     用于配置全局事务管理器

  •   TransactionDefinition接口是事务定义(描述)的对象,该对象中定义了事务规则,并提供了获取事务相关信息的方法,具体如下:

        String getName( );                     获取事务对象名称
        int getIsolationLevel( );             获取事务的隔离级别
        int getPropagationBehavior( );  获取事务的传播行为
        int getTimeout( );                      获取事务的超时时间
        boolean isReadOnly( );             获取事务是否只读

  • TransactionStatus接口是事务的状态,它描述了某一时间点上事务的状态信息。该接口中包含6个方法,具体如下:

        void flush();                            刷新事务
        boolean hasSavepoint();         获取是否存在保存点
        boolean isCompleted();          获取事务是否完成
        boolean isNewTransaction(); 获取是否为新事务
        boolean isRollbackOnly();     获取事务是否回滚
        void setRollbackOnly();         设置事务回滚


Spring事务管理的两种方式

    编程式事务管理,通过编写代码实现的事务管理,包括定义事务的开始、正常执行后的事务提交和异常时的事务回滚
    声明式事务管理,通过AOP技术实现的事务管理,主要思想是将事务作为一个“切面”代码单独编写,然后通过AOP技术将事务管理的“切面”植入到业务目标类中

     Spring的声明式事务管理可以通过两种方式来实现,一种是基于XML的方式,另一种是基于Annotation的方式。

基于XML的方式

基于XML方式的声明式事务是在配置文件中通过<tx:advice>元素配置事务规则来实现的。当配置了事务的增强处理后,就可以通过编写的AOP配置,让Spring自动对目标生成代理。

       配置<tx:advice>元素的重点是配置<tx:method>子元素,上图中使用灰色标注的几个属性是<tx:method>元素中的常用属性。其属性描述具体如下

 

<?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" 
    xmlns:context="http://www.springframework.org/schema/context"
    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/context 
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- 1.配置数据源 -->
    <bean id="dataSource" 
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<!--数据库驱动 -->
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<!--连接数据库的url -->
		<property name="url" value="jdbc:mysql://localhost/spring" />
		<!--连接数据库的用户名 -->
		<property name="username" value="root" />
		<!--连接数据库的密码 -->
		<property name="password" value="root" />
   </bean>
   <!-- 2.配置JDBC模板 -->
   <bean id="jdbcTemplate" 
          class="org.springframework.jdbc.core.JdbcTemplate">
		 <!-- 默认必须使用数据源 -->
		 <property name="dataSource" ref="dataSource" />
   </bean>
   <!--3.定义id为accountDao的Bean -->
   <bean id="accountDao" class="com.itheima.jdbc.AccountDaoImpl">
		 <!-- 将jdbcTemplate注入到AccountDao实例中 -->
		 <property name="jdbcTemplate" ref="jdbcTemplate" />
   </bean>	
   <!-- 4.事务管理器,依赖于数据源 -->
   <bean id="transactionManager" class=
   "org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
   </bean>	
   <!-- 5.编写通知:对事务进行增强(通知),需要编写对切入点和具体执行事务细节 -->
   <tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<!-- name:*表示任意方法名称 -->
			<tx:method name="*" propagation="REQUIRED" 
                           isolation="DEFAULT" read-only="false" />
		</tx:attributes>
	</tx:advice>
	<!-- 6.编写aop,让spring自动对目标生成代理,需要使用AspectJ的表达式 -->
	<aop:config>
		<!-- 切入点 -->
		<aop:pointcut expression="execution(* com.jdbc.*.*(..))" id="txPointCut" />
		<!-- 切面:将切入点与通知整合 -->
		<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut" />
	</aop:config>
</beans>

事务:

	public void transfer(String outUser, String inUser, Double money) {
	    // 收款时,收款用户的余额=现有余额+所汇金额
	    this.jdbcTemplate.update("update account set balance = balance +? "
	            + "where username = ?",money, inUser);
	    // 模拟系统运行时的突发性问题
	    int i = 1/0;
	    // 汇款时,汇款用户的余额=现有余额-所汇金额
	    this.jdbcTemplate.update("update account set balance = balance-? "  + "where username = ?",money, outUser);
	}

基于Annotation方式的声明式事务

1:在Spring容器中注册事务注解驱动
   <tx:annotation-driven transaction-manager="transactionManager"/>
2:在需要事务管理的类或方法上使用@Transactional注解
   如果将注解添加在Bean类上,则表示事务的设置对整个Bean类的所有方法都起作用;
   如果将注解添加在Bean类中的某个方法上,则表示事务的设置只对该方法有效。
如果将注解添加在Bean类上,则表示事务的设置对整个Bean类的所有方法都起作用;如果将注解添加在Bean类中的某个方法上,则表示事务的设置只对该方法有效。

<?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" 
    xmlns:context="http://www.springframework.org/schema/context"
    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/context 
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- 1.配置数据源 -->
    <bean id="dataSource" 
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<!--数据库驱动 -->
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<!--连接数据库的url -->
		<property name="url" value="jdbc:mysql://localhost/spring" />
		<!--连接数据库的用户名 -->
		<property name="username" value="root" />
		<!--连接数据库的密码 -->
		<property name="password" value="root" />
	</bean>
	<!-- 2.配置JDBC模板 -->
	<bean id="jdbcTemplate" 
            class="org.springframework.jdbc.core.JdbcTemplate">
		<!-- 默认必须使用数据源 -->
		<property name="dataSource" ref="dataSource" />
	</bean>
	<!--3.定义id为accountDao的Bean -->
	<bean id="accountDao" class="com.jdbc.AccountDaoImpl">
		<!-- 将jdbcTemplate注入到AccountDao实例中 -->
		<property name="jdbcTemplate" ref="jdbcTemplate" />
	</bean>
	<!-- 4.事务管理器,依赖于数据源 -->
	<bean id="transactionManager" class=
     "org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>	
    <!-- 5.注册事务管理器驱动 -->
	<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

基于注解事务:

@Transactional(propagation = Propagation.REQUIRED, 
            isolation = Isolation.DEFAULT, readOnly = false)
	public void transfer(String outUser, String inUser, Double money) {
	    // 收款时,收款用户的余额=现有余额+所汇金额
	    this.jdbcTemplate.update("update account set balance = balance +? "
	            + "where username = ?",money, inUser);
	    // 模拟系统运行时的突发性问题
	    int i = 1/0;
	    // 汇款时,汇款用户的余额=现有余额-所汇金额
	    this.jdbcTemplate.update("update account set balance = balance-? "
	            + "where username = ?",money, outUser);
	}

 

标签:事务管理,事务,Spring,update,接口,学习,balance
来源: https://blog.csdn.net/huanglu0314/article/details/111090081

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有