环境搭建
回顾事务基本概念
事务是数据库操作的基本单元,对其的执行操作,要么都成功,要么都失败。
四大特性(ACID):原子性、一致性、隔离性、持久性。
假设现在需要完成对下表操作,搭建一个基础环境,使a向b转账500。
第一步:xml配置
上个JdbcTemplate博客中都有讲,基本都是一样的。
- 组件扫描
- 数据库连接池配置
- JdbcTemplate对象创建,并注入数据库连接池属性。
<?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"
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">
<!--开启组件扫描-->
<context:component-scan base-package="spring5_2"></context:component-scan>
<!--配置数据库连接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
<property name="url" value="jdbc:mysql:///test" />
<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">
<!--注入dataSource-->
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
第二步:Service类和Dao类创建
- Service类进行业务操作
- Dao类进行数据库操作
UserService:注入UserDao属性,并将入账和出账业务放在一个方法中。
@Service
public class UserService {
@Autowired
private UserDao userDao;
public void accountMoney(){
//出账
userDao.reduceMoney();
//入账
userDao.addMoney();
}
}
UserDao接口:包含入账和出账方法。
public interface UserDao {
//出账
void reduceMoney();
//入账
void addMoney();
}
UserDaoImp1类:UserDao实现类,注入JdbcTemplate属性,操作数据库,并实现出账和入账的操作。
@Repository
public class UserDaoImp1 implements UserDao{
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public void reduceMoney() {
System.out.println("a出账");
String sql = "update userAccount set money=money-? where name=?";
jdbcTemplate.update(sql, 500, "a");
}
@Override
public void addMoney() {
System.out.println("b入账");
String sql = "update userAccount set money=money+? where name=?";
jdbcTemplate.update(sql,500,"b");
}
}
测试一下
public class TestXXX {
@Test
public void test1(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
UserService userService = context.getBean("userService", UserService.class);
userService.accountMoney();
}
}
结果:
注:学过事务的一定知道这是没有出现异常的情况下才会出现的结果,如果有异常就会转账失败,存在不安全的问题,那么我们就需要对这两个操作进行事务管理。
声明式事务管理
首先,在Spring进行声明式事务管理,底层使用的是AOP原理,并且注解和xml配置两种都可以实现。在Spring中提供了PlatformTransactionManager接口来做事务管理,针对于MySQL数据库连接池,我们可以是用DataSourceTransactionManager这个实现类。
注解方式
Spring配置
- 在xml文件中配置事务管理器
- 开启事务注解:1.先得引入名称空间tx,2.开启事务注解
<?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"
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">
<!--开启组件扫描-->
<context:component-scan base-package="spring5_2"></context:component-scan>
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置数据库连接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
<property name="url" value="jdbc:mysql:///test" />
<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">
<!--注入dataSource-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--开启事务注解-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>
添加注解
- @Transactional是事务的注解,可添加在类或者方法上。
- 添加在类上,代表这个类里所有的方法都添加事务。
- 添加在方法上面,是为这个方法添加事务
现在我们将UserService类上面添加事务注解,然后在两个操作中间添加一个异常查看情况。
@Service
@Transactional
public class UserService {
@Autowired
private UserDao userDao;
public void accountMoney(){
//出账
userDao.reduceMoney();
//模拟故障,产生异常
int i = 10/0;
//入账
userDao.addMoney();
}
}
结果:
从结果看出来,事务注解起到作用了,执行失败,回滚了。
@Transactional参数说明
1.propagation:事务传播行为
事务传播行为是多个事务方法直接进行调用,这个过程中事务是怎样进行管理的。对于事务方法就是指对数据库表产生变化的操作。
传播属性 | 描述 |
---|---|
REQUIRED | 如果有事务在运行,当前的方法就在这个事务内运行,否则,就启动一个新的事务,并在自己的事物内运行。 |
REQUIRED_NEW | 当前的方法必须启动新事务,并在它自己的事务内运行,如果有事务正在运行,应该将它挂起。 |
SUPPORTS | 如果有事务在运行,当前的方法就在这个事务内运行。否则它可以不运行在事务中。 |
NOT_SUPPORTED | 当前的方法不应该运行在事务中,如果有运行的事物,将它挂起。 |
MANDATORY | 当前的方法必须运行在事务内部,如果没有正在运行的事物,就抛出异常 |
NEVER | 当前的方法不应该运行在事务中,如果有运行的事务,就抛出异常。 |
NESTED | 如果有事务在运行,当前的方法就应该在这个事务的嵌套事务内运行,否则,就启动一个新的事务,并在它自己的事务内运行。 |
2.isolation:事务隔离级别
隔离级别 | 脏读 | 不可重复读 | 幻读 |
---|---|---|---|
READ UNCOMMITTED(读未提交) | 有 | 有 | 有 |
READ COMMITTED(读已提交) | 无 | 有 | 有 |
REPEATABLE READ(可重复读) | 无 | 无 | 有 |
SERIALIZABLE(串行化) | 无 | 无 | 无 |
3.timeout:超时时间
规定事务在一定时间内进行提交,如果不提交进行回顾,默认值是-1,设置时间以秒为单位进行计算。
4.readOnly:是否只读
默认值为false,表示可以进行增删改查,设置为true,只能查询
5.rollbackFor:回滚
设置出现哪些异常进行事务回滚
6.noRollbackFor:不回滚
设置出现哪些异常不进行事务回滚。
xml配置方式
刚才是使用@Transactional注解方式直接对类或者方法添加了注解,那么怎么用xml配置方式添加注解呢?我们之前提到对方法添加事务注解就是应用了AOP原理,所以按照AOP原理,我们需要配置通知,配置切入点和切面。
<!--配置事务管理器-->
<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:attributes>
</tx:advice>
<!--3.配置切入点和切面-->
<aop:config>
<!--配置切入点-->
<aop:pointcut id="pt" expression="execution(* spring5_2.service.UserService.*(..))"/>
<!--配置切面-->
<aop:advisor advice-ref="txadvice" pointcut-ref="pt"/>
</aop:config>
这样就可以不适用注解了,然后添加事务了。
完全注解方式
xml配置中的操作,都可以通过注解方式来完成,不过这里我们需要用到配置类来完成。
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
@Configuration//配置类
@ComponentScan(basePackages = "spring5_2")//组件扫描
@EnableTransactionManagement//开启事务
public class TxConfig {
//创建数据库连接池,返回的是一个Bean对象
@Bean
public DruidDataSource getDruidDataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql:///test");
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;
}
}