Spring 事务
什么是事务?
事务在百度百科中的解释为访问并可能更新数据库中各种数据项的一个程序执行单元。在关系数据库中,一个事务可以是一条sql语句、一组sql语句或整个程序,一个事务就是一个不可分割的执行单元,在一个事务中,要么全部执行,要么全部不执行。
事务具备原子性(A)、一致性(C)、隔离性(I)和持久性(D)这四大特性,至于这四大特性所表达的含义,不清楚的童鞋可自行百度。
我们经常会拿银行的转账业务来描述一个事务,当A要给B转账1000元时,需要完成的工作包括A的账户余额减少1000元和B的账号余额增加1000元,这一系列的工作便是一个事务,因此A账户余额的减少和B账户余额的增加要么全部执行,要么全部不执行。那么当A账户余额已经减少而B账户余额未增加时产生异常该如何处理?根据事务的特性,会将执行的操作进行回滚,回滚到原始状态,只有一个事务的所有工作都顺利完成时才会将事务提交。
Spring本身是没有事务的,事务实际上是数据库中的专业术语,Spring能够完成事务的管控也正是因为数据库对事务的支持。既然聊到了数据库,那么本次学习就必须进行数据库的连接,小伙伴们可以根据自己的方法来完成连接并成功操作数据库中的数据。
本次学习主要是学会如何使用spring的事务机制,以下提供了Spring基于XML配置的事务和基于注解的事务的基本实现。
基于xml配置的事务
实体类
Account.java
@Data
public class Account implements Serializable {
private Integer id;
private String name;
private Float money;
}
请读者在数据库创建对应数据库和数据表
持久层
AccountDao.java
@Repository("accountDao")
public class AccountDao extends JdbcDaoSupport {
@Autowired
JdbcTemplate jdbcTemplate;
public Account findAccountById(Integer accountId) {
List<Account> accounts = jdbcTemplate.query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),accountId);
return accounts.isEmpty()?null:accounts.get(0);
}
public Account findAccountByName(String accountName) {
List<Account> accounts = jdbcTemplate.query("select * from account where name = ?",new BeanPropertyRowMapper<Account>(Account.class),accountName);
if(accounts.isEmpty()){
return null;
}else if(accounts.size()>1){
throw new RuntimeException("结果集不唯一");
}else{
return accounts.get(0);
}
}
public void updateAccount(Account account) {
jdbcTemplate.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}
}
业务层
AccountService.java
@Service("accountService")
public class AccountService {
@Autowired
private AccountDao aDao;
public void setaDao(IAccountDao aDao) {
this.aDao = aDao;
}
public Account findAccountById(Integer accountId) {
return aDao.findAccountById(accountId);
}
public Account findAccountByName(String accountName) {
return aDao.findAccountByName(accountName);
}
public void updateAccount(Account account) {
aDao.updateAccount(account);
}
public void transfer(String sourceName, String targetName, Float money) {
//根据名称查询转出账户
Account sourceAccount = aDao.findAccountByName(sourceName);
//根据名称查询转入账户
Account targetAccount = aDao.findAccountByName(targetName);
//转出账户减钱
sourceAccount.setMoney(sourceAccount.getMoney()-money);
//转入账户加钱
targetAccount.setMoney(targetAccount.getMoney()+money);
//更新转出账户
aDao.updateAccount(sourceAccount);
int i = 1/0;
//更新转入账户
aDao.updateAccount(targetAccount);
}
}
xml配置
bean.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="accountService" class="cn.yz.service.AccountService">
<property name="aDao" ref="accountDao"></property>
</bean>
<!--配置账户的持久层-->
<bean id="accountDao" class="cn.yz.dao.AccountDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
<!--配置JdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/spring?characterEncoding=UTF-8&useUnicode=true&useSSL=false&tinyInt1isBit=false&serverTimezone=UTC"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!--配置事务管理器-->
<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="*" propagation="REQUIRED" read-only="false"/>
<tx:method name="find" propagation="REQUIRED" read-only="true"></tx:method>
</tx:attributes>
</tx:advice>
<!--配置aop-->
<aop:config>
<!--配置切入点表达式-->
<aop:pointcut id="pt1" expression="execution(* cn.yz.service.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
</aop:config>
</beans>
在以上的XML配置中,不仅配置了事务,还配置了AOP。实际上声明式事务就是基于AOP的,其本质上就是在方法的执行前后进行拦截,成功执行就提交,未成功执行完成就进行回滚。
以上配置中,基本的IOC对象和数据库的配置就不再进行讲解了。
对于事务的配置,首先需要一个事务管理器,即transactionManager,他绑定了特定的数据库,是对执行数据库的事务管理器。使用tx:advice标签来配置一个事务通知,其中的属性id为唯一标识,transaction-manager为以上配置的事务管理器transactionManager。
在tx:advice标签的内部tx:attributes表示配置事务的属性,其内的tx:method标签表示配置对某个方法的监控,一个tx:attributes标签的内部可以有多个tx:method标签。其中:
name 指定了方法的名称,可以用通配符*表示全部方法,指定确定名称的方法比使用通配符*的方法的优先级高;
isolation 指定事务的隔离级别,默认是DEFAULT,表示使用数据库的默认级别;
roolback-for 用于指定一个异常,当产生该异常时,事务回滚,产生其他异常时,事务不回滚,没有默认值,表示任何异常都回滚,no-rollback-for含义正好相反;
propagation 指定事务的传播行为 默认值是REQUIRED,表示一定会有事务,增删改的选择,查询方法可以使用SUPPORTS;
read-only 用于指定事务是否只读,只有查询方法才能设为只读,默认值为false,表示读写;
timeout 用于指定事务的超时时间,默认值是-1,表示永不超时,如果指定数值,以秒为单位。
在上一篇文章spring AOP中,配置切面时是使用< aop:aspect>标签,在进行事务管理时,我们需要使用**< aop:advisor>**标签来进行配置,需要注意的是,< aop:advisor>标签中引用的通知时,通知必须实现Advice接口,切入点的定义和上一篇spring AOP中类似。
测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {
@Autowired
private AccountService as;
@Test
public void testTransfer(){
as.transfer("aaa","bbb",500f);
}
}
运行结果
执行前数据库情况:
控制台打印:
执行后数据库情况:
当没有事务控制时,异常发生在aaa账户余额减去500以后,因此会出现aaa账户yue减少500而bbb账户yue并未增加的局面。但从结果可以看出,当发生异常时,在同一个事务中,即使已执行的操作也会发生回滚,因此aaa和bbb账户余额都没改变
基于注解的事务
相关注解:
@Transactional:声明式事务管理编程中使用的注解,在访问数据库的类或方法上添加该注解就能对类中相关方法的操作进行事务管理,需要注意的是,一定要开启对事务的支持该注解才会生效。
该注解中的属性配置同xml中类似,如isolation、readOnly、rollbackFor、timeout等等,可参考xml中的属性。
@EnableTransactionManagement:开启对事务的支持
本次实现是没有xml文件的,因此我们需要编写JDBC的配置类来连接数据
数据库配置类
JdbcConfig.java
public class JdbcConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
/**
* 创建JdbcTemplate对象
* @param dataSource
* @return
*/
@Bean(name="jdbcTemplate")
public JdbcTemplate createJdbcTemplate(DataSource dataSource){
return new JdbcTemplate(dataSource);
}
/**
* 创建数据源对象
* @return
*/
@Bean(name = "dataSource")
public DataSource createDataSource(){
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(username);
ds.setPassword(password);
return ds;
}
}
事务配置类
TransactionConfig.java
public class TransactionConfig {
/**
* 用于创建事务管理器对象
* @param dataSource
* @return
*/
@Bean(name="transactionManager")
public PlatformTransactionManager createTransactionManager(DataSource dataSource){
return new DataSourceTransactionManager(dataSource);
}
}
在Spring中提供了一个叫做PlatformTransactionManager接口,不同的数据访问技术都会对该接口进行实现,如下表所示:
数据库访问技术 | 实现 |
---|---|
JDBC | DataSourceTransactionManager |
JPA | JpaTransactionManager |
Hibernate | HibernateTransactionManager |
JDO | JdoTransactionManager |
分布式事务 | JtaTransactionManager |
主配置类
SpringConfiguration.java
@Configuration
@ComponentScan("cn.yz")
@Import({JdbcConfig.class,TransactionConfig.class})
@PropertySource("classpath:jdbcConfig.properties")
@EnableTransactionManagement
public class SpringConfiguration {
}
实体类Account和AccountDao的编写方式和XML方式下的一样,在此为节约篇幅不再赘述。
业务层
AccountService.java
@Service("accountService")
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)//只读型事务的配置
public class AccountService {
@Autowired
private AccountDao aDao;
public Account findAccountById(Integer accountId) {
return aDao.findAccountById(accountId);
}
public Account findAccountByName(String accountName) {
return aDao.findAccountByName(accountName);
}
//需要配置读写型的事务 读写和只读分布均匀且数量都较多时,用xml更加方便
@Transactional(propagation = Propagation.REQUIRED,readOnly = false)
public void updateAccount(Account account) {
aDao.updateAccount(account);
}
//需要配置读写型的事务
@Transactional(propagation = Propagation.REQUIRED,readOnly = false)
public void transfer(String sourceName, String targetName, Float money) {
//System.out.println("transfer...");
//2.1.根据名称查询转出账户
Account sourceAccount = aDao.findAccountByName(sourceName);
//2.2.根据名称查询转入账户
Account targetAccount = aDao.findAccountByName(targetName);
//2.3.转出账户减钱
sourceAccount.setMoney(sourceAccount.getMoney()-money);
//2.4.转入账户加钱
targetAccount.setMoney(targetAccount.getMoney()+money);
//2.5.更新转出账户aDao.updateAccount(sourceAccount);
aDao.updateAccount(sourceAccount);
int i = 1/0;
//2.6.更新转入账户
aDao.updateAccount(targetAccount);
}
}
测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {
@Autowired
private AccountService as;
@Test
public void testTransfer(){
as.transfer("aaa","bbb",500f);
}
}
结果同基于xml的事务的结果。
aDao.updateAccount(targetAccount);
}
}
#### 测试
```java
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {
@Autowired
private AccountService as;
@Test
public void testTransfer(){
as.transfer("aaa","bbb",500f);
}
}
结果同基于xml的事务的结果。
欢迎留言和指正😊