事务的概念
事务是数据库操作最基本单元,踏实对数据库一组操作,这组操作要么都成功,如果有一个失败所有操
作都失败。
事务四个特性(ACID)
(1)原子性:一个事务中的所有操作要么都成功,要么都不成功。
(2)一致性:数据总量在事务执行前后应保持不变。
(3)隔离性:一个事务的执行不能影响其它事务。
(4)持久性:事务一旦成功执行,对数据库的改变是永久的。
示例
模拟转账过程:数据库表如下:
dao层:
package com.jdbc.dao;
import org.springframework.stereotype.Repository;
@Repository
public interface Bank {
//减少前的数额
public void reduce(String userName,double count);
//增加钱的数额
public void add(String userName,double count);
}
package com.jdbc.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class BankImpl implements Bank{
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public void reduce(String userName, double count) {
String sql = "update count set count = count - ? where userName = ?";
jdbcTemplate.update(sql,count,userName);
}
@Override
public void add(String userName, double count) {
String sql = "update count set count = count + ? where userName = ?";
jdbcTemplate.update(sql,count,userName);
}
}
service层:
package com.jdbc.service;
import com.jdbc.dao.Bank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class BankService {
@Autowired
Bank bank;
public void transfer(String outUserName,String inUserName,double count) {
bank.reduce(outUserName,count);
bank.add(inUserName,count);
}
}
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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--开启注解扫描-->
<context:component-scan base-package="com.jdbc"></context:component-scan>
<!--创建连接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
destroy-method="close">
<property name="url" value="jdbc:mysql:///bank"/>
<property name="username" value="root"/>
<property name="password" value="root" />
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
</bean>
<!--创建jdbcTemplate对象-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
测试类:
package com.jdbc.test;
import com.jdbc.service.BankService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
@org.junit.Test
public void test() {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:Application.xml");
BankService service = context.getBean("bankService",BankService.class);
service.transfer("fan","xu",100);
}
}
执行结果:
存在的问题:如果在转账过程中出现异常?
package com.jdbc.service;
import com.jdbc.dao.Bank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class BankService {
@Autowired
Bank bank;
public void transfer(String outUserName,String inUserName,double count) {
bank.reduce(outUserName,count);
int i = 10 / 0;
bank.add(inUserName,count);
}
}
执行结果:可以看出fan转出了100,但是xu没有增加100
解决方案:添加事务
添加事务的流程:
try{
//开启事务
....
//逻辑代码
....
//事务提交
....
}catch(){
//事务回滚
....
}
spring事务操作
1、事务添加到 JavaEE 三层结构里面 Service 层(业务逻辑层)
2、在 Spring 进行事务管理操作
(1)有两种方式:编程式事务管理(上述中的添加事务的流程)和声明式事务管理(使用)
3、声明式事务管理
(1)基于注解方式(使用)
(2)基于 xml 配置文件方式
4、在 Spring 进行声明式事务管理,底层使用 AOP 原理
注解声明式事务管理
(1)创建事务管理器
<!--开启注解扫描-->
<context:component-scan base-package="com.jdbc"></context:component-scan>
<!--创建连接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
destroy-method="close">
<property name="url" value="jdbc:mysql:///bank"/>
<property name="username" value="root"/>
<property name="password" value="root" />
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
</bean>
<!--创建jdbcTemplate对象-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--创建事务管理器对象-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
(2)开启事务注解
2.1 在spring中引入tx命名空间
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
</beans>
2.2 开启事务注解
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
(3)在 service 类上面(或者 service 类里面方法上面)添加事务注解@Transactional,这个注解添加到类上面,也可以添加方法上面,如果把这个注解添加类上面,这个类里面所有的方法都添加事务,如果把这个注解添加到方法上面,为这个方法添加事务。
声明式事务注解参数配置
- propagation:事务传播行为
(1)多事务方法直接进行调用,这个过程中事务 是如何进行管理的(就是有事务的方法调没事务的方法或者有事务的方法、没事务的方法调用没事务的方法或者有事务的方法这个过程中事务应该如何管理)
- isolation :隔离级别,设置隔离级别的目的是为了在并发的环境下让不同的事务不相互影响,没有隔离级别会产生以下几个问题:
(1)读脏数据:一个事务读取另一个未提交事务修改过的数据。
如:事务A和事务B对同一条数据分别进行修改和读取操作,事务A修改数据但是未提交事务,此时事务B读取这一数据,但是由于某些原因事务A对这一数据的修改执行了回滚操作,此时事务B读取的就是未提交过的脏数据。
(2)不可重复度:一个事务读取了另一个事务提交过的修改数据。
如:事务A和事务B对同一条数据分别进行修改和读取操作,事务B先读取数据,后事务A修改数据并提交事务,此时数据库中的对应的数据就被修改了,这个时候事务B再次读取这一条数据,但是此时读取的数据和之前读取的数据已经不是同一条数据,这种情况就是不可重复读。
(3)幻读:一个未提交的事务读取到另一个未提交事务添加的数据。
如:事务A往数据库中添加了一条数据,但是事务A未提交,此时这条数据就被保存在缓存中,事务B恰好读取了这一条数据,但是之后事务A发生了回滚操作,这一条数据被撤销,这种情况就是幻读。
解决方案:设置隔离级别
3. timeout:超时时间
(1)事务需要在一定时间内进行提交,如果不提交进行回滚
(2)默认值是 -1 ,表示不超时,设置时间以秒单位进行计算
4. readOnly:是否只读
(1)读:查询操作,写:添加修改删除操作
(2)readOnly 默认值 false,表示可以查询,可以添加修改删除操作
(3)设置 readOnly 值是 true,设置成 true 之后,只能查询
5. rollbackFor:回滚
(1)设置出现哪些异常进行事务回滚
6. noRollbackFor:不回滚
(1)设置出现哪些异常不进行事务回滚
xml声明式事务管理
步骤:
- 配置事务管理器
- 配置通知
- 配置切入点和切面
<!--1 创建事务管理器--> <bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--2 配置通知-->
<tx:advice id="txadvice">
<!--配置事务参数-->
<tx:attributes>
<!--指定哪种规则的方法上面添加事务,就是需要添加事务的切入点-->
<tx:method name="accountMoney" propagation="REQUIRED"/>
<!--<tx:method name="account*"/>-->
</tx:attributes>
</tx:advice>
<!--3 配置切入点和切面-->
<aop:config>
<!--配置切入点-->
<aop:pointcut id="pt" expression="execution(*
com.atguigu.spring5.service.UserService.*(..))"/>
<!--配置切面-->
<aop:advisor advice-ref="txadvice" pointcut-ref="pt"/>
</aop:config>
完全注解式事务管理
利用配置类代替xml文件
、创建配置类,使用配置类替代 xml 配置文件
@Configuration //配置类
@ComponentScan(basePackages = "com.atguigu") //组件扫描
@EnableTransactionManagement //开启事务
public class TxConfig {
//创建数据库连接池
@Bean
public DruidDataSource getDruidDataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql:///user_db");
dataSource.setUsername("root");
dataSource.setPassword("root");
return dataSource;
}
//创建 JdbcTemplate 对象
@Bean
public JdbcTemplate getJdbcTemplate(DataSource dataSource) {
//到 ioc 容器中根据类型找到 dataSource
JdbcTemplate jdbcTemplate = new JdbcTemplate();
//注入 dataSource
jdbcTemplate.setDataSource(dataSource);
return jdbcTemplate;
}
//创建事务管理器
@Bean
public DataSourceTransactionManager
getDataSourceTransactionManager(DataSource dataSource) {
DataSourceTransactionManager transactionManager = new
DataSourceTransactionManager();
transactionManager.setDataSource(dataSource);
return transactionManager;
}
}