声明式事务
回顾事务
-
把一组业务当成一个事务来做;要么都成功,要么都失败
-
事务在项目开发中十分重要,涉及到数据一致性的问题
-
确保完整性和一致性
事务ACID原则:
- 原子性
- 一致性
- 隔离性
- 多个业务可能操作同一个资源,防止数据损坏
- 持久性
- 事务一旦提交,无论系统发生什么问题,结果都不会再被影响,被持久的写到存储器中
事务的配置
spring-dao.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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 获取数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="password" value="123456"/>
<property name="username" value="root"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8&useSSL=true"/>
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
</bean>
<!-- 获取sqlSessionFactory 通过SqlSessionFactoryBean-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 用到数据源-->
<property name="dataSource" ref="dataSource"/>
<!-- 绑定Mybatis配置文件 可有可无-->
<property name="configLocation" value="mybatis-config.xml"/>
<!-- <property name="mapperLocations" value="classpath:com/wjq/mapper/*.xml"/>-->
</bean>
<!--SqlSessionTemplate 就是我们所用到的SqlSession
public SqlSessionTemplate(SqlSessionFactory sqlSessionFactory){}
且没有set()-->
<!--方式二可以不用这步因为SqlSessionDaoSupport类里面会创建SqlSessionTemplate-->
<!-- <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">-->
<!-- <constructor-arg index="0" ref="sqlSessionFactory"/>-->
<!-- </bean>-->
<!-- 配置声明式事务-->
<bean id="transaction" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 结合aop实现事务的植入-->
<!-- 配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transaction">
<!-- 给哪些方法配置事务-->
<tx:attributes>
<!-- 配置事务的传播特性 默认也是REQUIRED-->
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--配置事务切入-->
<aop:config>
<aop:pointcut id="txPointcut" expression="execution(* com.wjq.mapper.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>
</beans>
Spring中的事务管理
- 声明式事务:AOP
- 编程式事务:需要在代码中,进行事务的管理
为什么需要事务?
- 如果不配置事务,可能存在数据提交不一致的情况
- 如果不在spring中去配置事务,我们就需要在代码中手动配置事务
- 事务在项目开发中十分重要,涉及到数据的一致性和完整性问题。