数据库事务
MySQL中的事务
1.原生的sql语句是关闭事务(对于增删改查都是没有开启事务的)mysql是关闭事务,但是Oracle数据库是自动的开启事务的
`use crm;
start transaction;//开启事务
create table userinfo3(
id int PRIMARY KEY auto_increment,
username varchar(100) not null);
rollback;//如果没有提交事务则自动的回滚事务`
2.mysql中事务的原理:
事务的特性
- 一致性
- 原子性
- 隔离性
- 持久性
事务并发产生的问题
脏读
,读取到没有提交的数据
幻读
在删除所有数据的同时,插入数据,导致似乎数据没有被完全的删除
不可重复读
两次读取的数据不一致
事务的隔离级别
- 读未提交1 没有解决脏读,幻读,不可重复读中的任何问题
- 读已提交2 没有解决幻读和不可重复读
- 可重复读4(mysql默认的隔离级别)为解决不可重复读问题
- 串行化8 解决事务并发产生的所有的问题,但是效率很低。
spring框架管理事务
1.spring针对不同的数据库框架设计出了不同的事务管理机制
2.platformTransactionManager接口的结构图
3.spring管理事务的内容
事务的隔离级别:1,2,4,8四种隔离级别,可以根据具体业务的需求设置隔离级别 |
---|
事务的传播行为,开发中一般直接选用Requeried,事务的传播行为指的是,service之间平行互调,使用事务的传播行为,一般这种业务需求很少 |
只读模式:根据具体的数据操作设置是否为只读模式 |
4.spring管理的事务的方式(这里以spring管理mybatis事务为例,给出注解方式)
##(1)xml配置方式
<!-- 配置事务管理 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事务的通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="save*" isolation="DEFAULT" propagation="REQUIRED" read-only="false" />
</tx:attributes>
</tx:advice>
<!-- 配置aop事务 -->
<aop:config>
<!-- 配置切点 -->
<aop:pointcut expression="execution(* com.cjb.demo.service.impl.CustomerServiceImpl.*(..))" id="point"/>
<!--配置切面 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="point"/>
</aop:config>
##(2)注解配置方式
<!-- 配置事务管理 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
类中标注注解
@Transactional
public class CustomerServiceImpl implements CustomerService