spring-事务控制

image-20201129164840012

编程式:自己写java代码,jdbc那里。

声明式:配置(不写java代码)。有xml 和 注解2种。

1.编程式事务控制相关对象

image-20201129165412984

image-20201129165629838

image-20201129165727617

image-20201129165835656

A业务方法 调用 B业务方法,B看A有没有事务

什么是传播行为?

image-20201129170538283

状态不需要配置。 事务传播行为 级别 需要配置。

平台事务管理器是个接口,只定义行为,不同的dao层有不同的实现。

平台事务管理器 + 事务定义对象 = 事务状态。

事务定义对象 封装一些参数的。

image-20201129171150132

2.基于XML的声明式事务控制

业务代码 和 事务控制 解耦,通过xml配置。

切点:业务方法

增强:事务增强

image-20201129171615644

例:银行转账

//这里是2个事务,需要1个事务控制住
public void transfer(String outMan,String inMan,double money){
    mAccountDao.out(outMan,money);
    mAccountDao.in(inMan,money);
}

切点是业务方法。

image-20201129185713351

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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
      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">


    <context:property-placeholder location="classpath:jdbc.properties"/>



    <bean id="source" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    bean>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="source"/>
    bean>

    <bean id="accountDao" class="com.ustc.dao.AccountDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    bean>
    <bean id="service" class="com.ustc.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"/>
    bean>

//事务管理器
    <bean id="taManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="source"/>
    bean>
    
   <tx:advice id="txAdvice" transaction-manager="taManager">
       <tx:attributes>
           <tx:method name="*"/>
       tx:attributes>
   tx:advice>

    
    
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(public void com.ustc.service.impl.*.*(..))">aop:advisor>
    aop:config>
beans>

注: aop:config 除了要命名空间外,还要导入相应的maven坐标aspectj

  • tx是事务,事务的属性,上面那要配置

image-20201129195708331

image-20201129195916496

image-20201129195934165

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!