事务管理是企业级应用程序开发中必不可少的技术, 用来确保数据的完整性和一致性.
事务就是一系列的动作, 它们被当做一个单独的工作单元. 这些动作要么全部完成, 要么全部不起作用。
事务的四个关键属性(ACID)
原子性(atomicity): 事务是一个原子操作, 由一系列动作组成. 事务的原子性确保动作要么全部完成要么完全不起作用.
一致性(consistency): 一旦所有事务动作完成, 事务就被提交. 数据和资源就处于一种满足业务规则的一致性状态中.
隔离性(isolation): 可能有许多事务会同时处理相同的数据, 因此每个事物都应该与其他事务隔离开来, 防止数据损坏.
持久性(durability): 一旦事务完成, 无论发生什么系统错误, 它的结果都不应该受到影响. 通常情况下, 事务的结果被写到持久化存储器中.
Spring 的核心事务管理抽象是 org.springframework.transaction.PlatformTransactionManager 它为事务管理封装了一组独立于技术的方法. 无论使用 Spring 的哪种事务管理策略(编程式或声明式), 事务管理器都是必须的.
<?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:p="http://www.springframework.org/schema/p"
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-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
">
<!-- 扫描类 -->
<context:component-scan base-package="cn"></context:component-scan>
<!-- 加载jdbc 配置文件-->
<context:property-placeholder location="classpath:/cn/zj/lesson04/thing/config.properties"/>
<!-- 获取 jdbc 数据源 连接操作 -->
<bean id="dateSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="url" value="${url}"></property>
<property name="driverClassName" value="${driverClass}"></property>
<property name="username" value="${userAccount}"></property>
<property name="password" value="${passWord}"></property>
</bean>
<!-- 操作数据库 -->
<bean id="jdbcTemp" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dateSource"></property>
</bean>
<!--
事务 管理器 事务 和数据操作分不开所以要调取事务 通过调取数据源 -->
<bean id="transaction" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dateSource"></property></bean><tx:advice id="advices" transaction-manager="transaction"><tx:attributes><tx:method name="update*" propagation="REQUIRES"/><tx:method name="add*" propagation="REQUIRES"/></tx:attributes></tx:advice><!-- 定位切点 --><aop:config>
<!-- *代表任意多, 第一个* 是返回值类型 包名后面的第一个*是所有类名 第二个* 是方法名-->
<aop:pointcut expression="execution(* cn.*..*.包名.*.*(..))" id="aspects" />
<aop:advisor advice-ref="advices" pointcut-ref="aspects"/>
</aop:config>
</beans>