9、声明事务

9.1事务

  • 把一组组业务当成一个业务来做,要么成功,要么失败
  • 事务在项目开发中十分重要,涉及到数据的一致性问题
  • 确保数据的完整性和一致性

事务ACID原则

  • 原子性

  • 一致性

  • 隔离性

    多个业务可能 操作同一资源,防止数据损坏

  • 持久性

    事务一旦提交,无论系统发生什么问题,结果都不会被影响,被持久化的写在了存储器中

9.2Spring中的事务管理

  • 声明事务 :AOP
  • 编程式事务:需要在代码中,进行事务的管理

思考:为什么需要事务?

  • 如果不配置事务,可能存在数据提交不一致的情况下 ;
  • 如果我们不在Spring中去配置 声明式事务,我们就需要在代码中手动配置事务;
  • 事务在项目的开发中十分重要,涉及到数据的一致性和完整性问题.

实现(只要在spring-dao.xml中进行配置)

spring-dao.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans 
    <!--DataSource:使用Spring的数据源替换Mybatis的配置  c3p0 dbcp druid 我们这里使用Spring提供的JDBC:org.springframework.jdbc.datasorce-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSl=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>
    <!--配置sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--绑定mybatis核心配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:com/dong/mapper/*.xml"/>
    </bean>
    <!--SqlSessionTemplate:就是我们 以前使用的sqlSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!--只能使用构造器注入 sqlSessionFactory,因为它没有set方法-->
        <constructor-arg index="0"  ref="sqlSessionFactory"/>
    </bean>
    <!--配置声明式事务-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--结合AOP实现事务的织入-->
    <!--1.配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--2.配置:需要给哪一些方法配置事务-->
        <tx:attributes>
            <tx:method name="addUser" propagation="REQUIRED"/>
            <tx:method name="delUser" propagation="REQUIRED"/>
            <tx:method name="updUser" propagation="REQUIRED"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
    <!--3.配置事务切入-->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.dong.mapper.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>
</beans>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容