Spring中事务的XML方式[声明方式]

事务管理: 管理事务,管理数据,数据完整性和一致性

事务[业务逻辑] : 由一系列的动作[查询书价格,更新库存,更新余额],组成一个单元[买书业务],

当我们动作当中有一个错了,全错~

ACID

原子性 隔离性 一致性 持久性

   

注解方式配置事务[编程方式-->@代码]

1.Spring框架当中需要配置事务管理器--> JDBC[Mybatis] Hibernate JTA-->数据源

2.启动事务注解[特意说了,事务管理器的id]

3.事务注解--> 可以放置的位置:@Transaction 类或者方法上

  1. 类上放置注解 方法当中注解[reaonly=true]
  2. rollbakFor
  3. 传播性 7个 默认值

XML方式配置事务

复制代码
<!--声明方式XML方式:完成事务的配置,需要使用到地方有AOP-->
<!-- 配置事务管理器 -->

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

<property name="dataSource" ref="dataSource"/>

</bean>

<!-- 定义哪些方法需要被事务管理器进行管理 -->

<tx:advice id="serviceMethodAdvice" transaction-manager="transactionManager">

<tx:attributes>

<tx:method name="*" read-only="true"/>

</tx:attributes>

</tx:advice>

<!-- 需要哪些方法是被监控,并且是有事务管理 -->

<aop:config>

<aop:pointcut expression="execution(* com..service.*Service.*(..))" id="servicePointCut"/>

<!-- 代表的意思: service包下的说有类以Service结尾的类下的所有方法,都为只读状态 -->

<aop:advisor advice-ref="serviceMethodAdvice" pointcut-ref="servicePointCut"/>

</aop:config>
复制代码

单元测试,推荐使用断言方式,需要再使用syso(alt+/)的输出方式

复制代码
<!-- 定义哪些方法需要被事务管理器进行管理 -->

<tx:advice id="serviceMethodAdvice" transaction-manager="transactionManager">

<tx:attributes>

<!-- 约定大于配置 -->

<!-- 第一种配置方式

<tx:method name="*" read-only="true"/>

<tx:method name="add*" propagation="REQUIRED"/>

<tx:method name="insert*"/>

<tx:method name="create*"/>

<tx:method name="update*"/>

<tx:method name="edit*"/>

<tx:method name="mod*"/>

<tx:method name="change*"/>

<tx:method name="del*"/>

<tx:method name="remove*"/>

<tx:method name="cancel*"/>

-->

<!-- 第二种配置方式 -->

<tx:method name="*" read-only="false" />

<tx:method name="get*" read-only="true"/>

<tx:method name="load*" read-only="true"/>

<tx:method name="list*" read-only="true"/>

<tx:method name="find*" read-only="true"/>

<tx:method name="sel*" read-only="true"/>

<tx:method name="query*" read-only="true"/>

</tx:attributes>
</tx:advice>
复制代码

在这里想说的,帮助文档一定要看的!

重点: 绝对是个人的建议 
 
RuntimeException默认是不受审查,也是rollBackFor的默认值,如果你再Service层或者Dao层对其进行捕获的话,那么一定要做处理

个人的建议为: service和Dao不管遇到什么请求你都处理往外抛, 处理都放置在Controller 关于异常尽量都是用继承RuntimeException,根据你的代码情况进行不同异常的封装
原文地址:https://www.cnblogs.com/smallfa/p/10640570.html