一、Spring中事务控制常用API
1.PlatformTransactionManager
spring 的事务管理器,提供了常用的操作事务的方法:
①获取事务状态信息TransactionStatus getTransaction(TransactionDefinition definition)
②提交事务void commit(TransactionStatus status)
③回滚事务void rollback(TransactionStatus status)
使用SpringJDBC或myBatis进行持久化数据时使用:org.springframework.jdbc.datasource.DataSourceTransactionManager
使用Hibernate进行持久化数据时使用:org.springframework.orm.hibernate5.HibernateTransactionManager
2.TransactionDefinition
事务的定义信息对象,常用方法:
①获取事务对象名称:String getName()
②获取事务隔离级别:int getIsolationLevel()
③获取事务传播行为:int getPropagationBehavior()
④获取事务超时时间:int getTimeout()
⑤获取事务是否只读:boolean isReadOnly()
2.1事务隔离级别
事务隔离级别反映事务提交并发访问时的处理方式
①默认级别:ISOLATION_DEFAULt
②可以读取未提交数据:ISOLATION_READ_UNCOMMITTED
③只能读取已提交数据,解决脏读问题(Oracle默认级别):ISOLATION_READ_COMMITTED
④是否读取其他事务提交修改后的数据,解决不可重复读问题(MySql默认级别):ISOLATION_REPEATABLE_READ
⑤是否读取其他事务提交添加后的数据,解决幻读问题:ISOLATION_SERIALIZABLE
2.2事务的传播行为
-
REQUIRED
:如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。(默认值) -
SUPPORTS
:支持当前事务,如果当前没有事务,就以非事务方式执行(没有事务) -
MANDATORY
:使用当前的事务,如果当前没有事务,就抛出异常 -
REQUERS_NEW
:新建事务,如果当前在事务中,把当前事务挂起 -
NOT_SUPPORTED
:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起 -
NEVER
:以非事务方式运行,如果当前存在事务,抛出异常 -
NESTED
:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行REQUIRED
类似的操作
2.3超时时间
默认值是-1,没有超时限制。如果有,以秒为单位进行设置。
2.4是否是只读事务
查询时建议设置为只读。
3.TransactionStatus
提供的事务具体的运行状态,描述某个时间点上事务对象的状态信息,包含6个操作:
- 刷新事务:
void flush()
- 获取是否是存在的存储点:
boolean hasSavepoint()
- 获取事务是否完成:
boolean isCompleted()
- 获取事务是否为新的事务:
boolean isNewTransaction()
- 获取事务是否回滚:
boolean isRollbackOnly()
- 设置事务回滚:
void setRollbackOnly()
二、基于xml的声明式事务管理
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.hcx</groupId>
<artifactId>springtx</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.10</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
</dependencies>
</project>
beans.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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--配置账户的业务层-->
<bean id="accountService" class="com.hcx.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
<!-- 配置账户的持久层-->
<bean id="accountDao" class="com.hcx.dao.impl.AccountDaoImpl">
<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/myexecise"></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命名空间约束、aop约束-->
<!--
id:事务通知唯一标识
transaction-manager:为事务通知提供事务管理器
-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!-- 第五步:配置事务的属性
isolation:指定事务的隔离级别。默认值是DEFAULT,表示使用数据库的默认隔离级别。
propagation:指定事务的传播行为。默认值是REQUIRED,表示一定会有事务,增删改的选择。查询方法可以选择SUPPORTS。
read-only:指定事务是否只读。只有查询方法才能设置为true。默认值是false,表示读写。
timeout:指定事务的超时时间,默认值是-1,表示永不超时。如果指定了数值,以秒为单位。
rollback-for:指定一个异常,当产生该异常时,事务回滚,产生其他异常时,事务不回滚。没有默认值,表示任何异常都回滚。
no-rollback-for:指定一个异常,当产生该异常时,事务不回滚,产生其他异常时事务回滚。没有默认值,表示任何异常都回滚。
-->
<tx:attributes>
<tx:method name="*" propagation="REQUIRED" read-only="false"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"></tx:method>
</tx:attributes>
</tx:advice>
<!-- 第三步:配置aop-->
<aop:config>
<!-- 配置切入点表达式-->
<aop:pointcut id="pt1" expression="execution(* com.hcx.service.impl.*.*(..))"></aop:pointcut>
<!--第四步:建立切入点表达式和事务通知的对应关系 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
</aop:config>
<!--============================================事务配置结束=====================================================-->
</beans>
AccountService:
public interface AccountService {
Account findAccountById(Integer accountId);
/**
* 转账
* @param source 转出账户
* @param target 转入账户
* @param money 金额
*/
void transfer(String source,String target,Float money);
}
AccountServiceImpl:
public class AccountServiceImpl implements AccountService{
private AccountDao accountDao;
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public Account findAccountById(Integer accountId) {
return accountDao.selectAccountById(accountId);
}
@Override
public void transfer(String source, String target, Float money) {
Account sourceAccount = accountDao.selectAccountByName(source);
Account targetAccount = accountDao.selectAccountByName(target);
sourceAccount.setMoney(sourceAccount.getMoney()-money);
targetAccount.setMoney(targetAccount.getMoney()+money);
accountDao.updateAccount(sourceAccount);
//异常,设置了事务,失败了,则前面的操作可以回滚
int i= 1/0;
accountDao.updateAccount(targetAccount);
}
}
AccountDao:
public interface AccountDao {
Account selectAccountById(Integer accountId);
Account selectAccountByName(String name);
void updateAccount(Account account);
}
AccountDaoImpl:
public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {
@Override
public Account selectAccountById(Integer id) {
List<Account> accounts = getJdbcTemplate().query("SELECT * FROM account WHERE id=?",
new BeanPropertyRowMapper<>(Account.class), id);
return accounts.isEmpty()?null:accounts.get(0);
}
@Override
public Account selectAccountByName(String name) {
List<Account> accounts = getJdbcTemplate().query("SELECT * FROM account WHERE name=?",
new BeanPropertyRowMapper<>(Account.class), name);
if(accounts.isEmpty()){
return null;
}else if(accounts.size()>1){
throw new RuntimeException("多条结果");
}else {
return accounts.get(0);
}
}
@Override
public void updateAccount(Account account) {
getJdbcTemplate().update("UPDATE account SET name=?,money=? WHERE id=?",account.getName(),account.getMoney(),account.getId());
}
}
测试:
package com.hcx.test;
import com.hcx.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Created by hongcaixia on 2019/2/25.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:beans.xml")
public class AccountServiceTest {
@Autowired
private AccountService accountService;
@Test
public void testTransfer(){
accountService.transfer("hcx","xh",200f);
}
}
三、基于注解的声明式事务管理
beans.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"
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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--配置spring创建容器要扫描的包-->
<context:component-scan base-package="com.hcx"></context:component-scan>
<!--配置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/myexecise"></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>
<!-- 第二步:开启spring对注解事务的支持-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
<!--第三步:在需要使用事务的地方使用@Transactional注解-->
<!--============================================事务配置结束=====================================================-->
</beans>
AccountDaoImpl:
package com.hcx.dao.impl;
import com.hcx.dao.AccountDao;
import com.hcx.domain.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Created by hongcaixia on 2019/2/25.
*/
@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public Account selectAccountById(Integer id) {
List<Account> accounts = jdbcTemplate.query("SELECT * FROM account WHERE id=?",
new BeanPropertyRowMapper<>(Account.class), id);
return accounts.isEmpty()?null:accounts.get(0);
}
@Override
public Account selectAccountByName(String name) {
List<Account> accounts = jdbcTemplate.query("SELECT * FROM account WHERE name=?",
new BeanPropertyRowMapper<>(Account.class), name);
if(accounts.isEmpty()){
return null;
}else if(accounts.size()>1){
throw new RuntimeException("多条结果");
}else {
return accounts.get(0);
}
}
@Override
public void updateAccount(Account account) {
jdbcTemplate.update("UPDATE account SET name=?,money=? WHERE id=?",account.getName(),account.getMoney(),account.getId());
}
}
AccountServiceImpl:
package com.hcx.service.impl;
import com.hcx.dao.AccountDao;
import com.hcx.domain.Account;
import com.hcx.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
/**
* Created by hongcaixia on 2019/2/25.
*/
@Service("accountService")
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true) //只读型:执行查询时也会开启事务
public class AccountServiceImpl implements AccountService{
@Autowired
private AccountDao accountDao;
@Override
public Account findAccountById(Integer accountId) {
return accountDao.selectAccountById(accountId);
}
@Transactional(propagation = Propagation.REQUIRED,readOnly = false) //读写型:增删改开启事务
@Override
public void transfer(String source, String target, Float money) {
Account sourceAccount = accountDao.selectAccountByName(source);
Account targetAccount = accountDao.selectAccountByName(target);
sourceAccount.setMoney(sourceAccount.getMoney()-money);
targetAccount.setMoney(targetAccount.getMoney()+money);
accountDao.updateAccount(sourceAccount);
//异常
int i= 1/0;
accountDao.updateAccount(targetAccount);
}
}
四、纯注解的声明式事务管理
配置类JdbcConfig:
package com.hcx.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;
/**
* 数据库配置类
* Created by hongcaixia on 2019/2/25.
*/
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 dmds = new DriverManagerDataSource();
dmds.setDriverClassName(driver);
dmds.setUrl(url);
dmds.setUsername(username);
dmds.setPassword(password);
return dmds;
}
}
配置类TransactionConfig:
package com.hcx.config;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
/**
* 事务配置类
* Created by hongcaixia on 2019/2/25.
*/
public class TransactionConfig {
/**
* 创建事务管理器对象
* @param dataSource
* @return
*/
@Bean(name = "transactionManager")
public PlatformTransactionManager createTransactionManager(DataSource dataSource){
return new DataSourceTransactionManager(dataSource);
}
}
总配置SpringConfiguration:
package com.hcx.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* Spring的配置类,相当于beans.xml
* Created by hongcaixia on 2019/2/25.
*/
@Configuration
@ComponentScan("com.hcx")
@Import({JdbcConfig.class,TransactionConfig.class})
@PropertySource("jdbcConfig.properties")
@EnableTransactionManagement //开启事务注解支持
public class SpringConfiguration {
}
jdbcConfig.properties:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/myexecise
jdbc.username=root
jdbc.password=root
测试AccountServiceTest:
package com.hcx.test;
import com.hcx.config.SpringConfiguration;
import com.hcx.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Created by hongcaixia on 2019/2/25.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {
@Autowired
private AccountService accountService;
@Test
public void testTransfer(){
accountService.transfer("hcx","xh",200f);
}
}
五、spring编程式事务控制
AccountDaoImpl:
package com.hcx.dao.impl;
import com.hcx.dao.AccountDao;
import com.hcx.domain.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import java.util.List;
/**
* Created by hongcaixia on 2019/2/25.
*/
public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao{
@Override
public Account selectAccountById(Integer id) {
List<Account> accounts = getJdbcTemplate().query("SELECT * FROM account WHERE id=?",
new BeanPropertyRowMapper<>(Account.class), id);
return accounts.isEmpty()?null:accounts.get(0);
}
@Override
public Account selectAccountByName(String name) {
List<Account> accounts = getJdbcTemplate().query("SELECT * FROM account WHERE name=?",
new BeanPropertyRowMapper<>(Account.class), name);
if(accounts.isEmpty()){
return null;
}else if(accounts.size()>1){
throw new RuntimeException("多条结果");
}else {
return accounts.get(0);
}
}
@Override
public void updateAccount(Account account) {
getJdbcTemplate().update("UPDATE account SET name=?,money=? WHERE id=?",account.getName(),account.getMoney(),account.getId());
}
}
AccountServiceImpl:
package com.hcx.service.impl;
import com.hcx.dao.AccountDao;
import com.hcx.domain.Account;
import com.hcx.service.AccountService;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionTemplate;
/**
* Created by hongcaixia on 2019/2/25.
*/
public class AccountServiceImpl implements AccountService{
private AccountDao accountDao;
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
private TransactionTemplate transactionTemplate;
public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
this.transactionTemplate = transactionTemplate;
}
@Override
public Account findAccountById(Integer accountId) {
return transactionTemplate.execute((TransactionStatus status)->{
return accountDao.selectAccountById(accountId);
});
}
@Override
public void transfer(String source, String target, Float money) {
transactionTemplate.execute((TransactionStatus status)->{
Account sourceAccount = accountDao.selectAccountByName(source);
Account targetAccount = accountDao.selectAccountByName(target);
sourceAccount.setMoney(sourceAccount.getMoney()-money);
targetAccount.setMoney(targetAccount.getMoney()+money);
accountDao.updateAccount(sourceAccount);
//异常
int i= 1/0;
accountDao.updateAccount(targetAccount);
return null;
});
}
}
beans.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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 配置业务层-->
<bean id="accountService" class="com.hcx.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
<property name="transactionTemplate" ref="transactionTemplate"></property>
</bean>
<!-- 配置账户的持久层-->
<bean id="accountDao" class="com.hcx.dao.impl.AccountDaoImpl">
<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/myexecise"></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>
<!--事务模板对象-->
<bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
<property name="transactionManager" ref="transactionManager"></property>
</bean>
</beans>
AccountServiceTest:
package com.hcx.test;
import com.hcx.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Created by hongcaixia on 2019/2/25.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:beans.xml")
public class AccountServiceTest {
@Autowired
private AccountService accountService;
@Test
public void testTransfer(){
accountService.transfer("hcx","xh",200f);
}
}
弊端:出现了重复代码(不建议使用)

网友评论