1、what 是 声明式事务?
只需要告诉Spring,哪些方法是事务方法,剩下的事情。回滚,提交。关闭/获取资源Spring自动干预。
底层叫事务管理器,他就是一个事务切面。他能在合适的时机自动切入目标方法,自动回滚,提交等
2、声明式事务 的2种配置方式之注解
——》》1、配置事务管理器,DataSourceTransactionManager 控制连接
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入连接池信息-->
<property name="dataSource" ref="pooledDataSource"></property>
</bean>
——》》2、开启基于注解的事务控制 tx:transaction-manager:指定事务管理器
<tx:annotation-driven transaction-manager="transactionManager"/>
——》》3、transactional注解声明这个方法是事务方法
@Transactional
public void checkout(String isbn,String username){
//减库存
bookDao.updateStock(isbn);
//减余额
int byIsbn = bookDao.getPriceByIsbn(isbn);
int i=10/0;
}
如果事务管理器的名字就是transactionManager,可以不用指定
必须导入切面相关.aspect,和增强版的三个
3、声明式事务 的2种配置方式之XML 配置
————1、 引入加入业务组件
<bean id="bookDao" class="com.atguigu.dao.BookDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
<bean id="bookService" class="com.atguigu.service.BookService">
<property name="bookDao" ref="bookDao"></property>
</bean>
<bean id="mulService" class="com.atguigu.service.MulService">
<property name="bookService" ref="bookService"></property>
</bean>
———》》2、.xml的配置事务管理器
1)、配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" value="#{dataSource}"></property>
</bean>
2)、使用xml配置事务 aop名称空间–>
<aop:config>
<!--说明哪些方法要切入事务 -->
<aop:pointcut expression="execution(* com.atguigu.service.BookService.*(..))" id="txPoint"/>
<aop:pointcut expression="execution(* com.atguigu.service.MulService.*(..))" id="txPoint2"/>
<!--配置事务建议:
1、advice-ref="myAdvice":指向的事务建议
2、在运行pointcut-ref="txPoint"方法的时候,去执行事务建议
3、tx:method:设置每一个要执行的方法的建议
-->
<aop:advisor advice-ref="myAdvice" pointcut-ref="txPoint"/>
<aop:advisor advice-ref="myAdvice" pointcut-ref="txPoint2"/>
</aop:config>
3)、配置一个事务建议:运行事务的时候,该怎么运行。事务超时属性,传播行为
<tx:advice id="myAdvice" transaction-manager="transactionManager">
<!-- 事务属性 -->
<tx:attributes>
<!--配置每一个事务方法
name:写方法名
-->
<tx:method name="checkout" timeout="6"/>
<!-- 就相当于给这个方法加上了一个@Transactional注解 -->
<tx:method name="*"/>
<!-- 所有以get开始的方法,都是只读方法 -->
<tx:method name="get*" read-only="true"/>
</tx:attributes>
</tx:advice>
4、 声明式事务和编程式事务的区别
编程式事务就是自己写Try catch语句调用commit\rollback等函数来实现那段业务数据改变的事务性。
filter{
//1、获取连接
//2、开启非自动提交
try{
//3、放行方法
//4、提交事务
}catch(Exception e){
//5、回滚事务
}finally{
//6、释放资源
}
}