PlatformTransactionManager:接口,提供事务操作的方法,包含有3个具体的操作:
TransactionStatus getTransaction(TransactionDefinition definition)
:获取事务状态信息
void commit(TransactionStatus status)
:提交事务
void rollback(TransactionStatus status)
:回滚事务
开发中都是使用它的实现类,它们是真正管理事务的对象 ,如:
org.springframework.jdbc.datasource.DataSourceTransactionManager
: 使用Spring JDBC或iBatis 进行持久化数据时使用org.springframework.orm.hibernate5.HibernateTransactionManager
:使用Hibernate版本进行持久化数据时使用TransactionDefinition :事务的定义信息对象,包含如下方法:
String getName()
:获取事务名称int getIsolationLevel()
:获取事务的隔离级别int getPropagationBerhavior()
:获取事务的传播行为int getTimeout()
:获取事务的超过时间boolean isReadOnly()
:获取事务是否只读TransactionStatus:接口,描述某个时间点上事务对象的状态信息,包含6个具体的操作:
void flush()
:刷新事务
boolean hasSavepoint()
:获取是否存在存储点
boolean isCompleted()
:获取事务是否完成
boolean isNewTransaction()
:获取事务是否是新的事务
boolean isRollbackOnly()
:获取事务回滚
void setRollbackOnly()
:设置事务回滚
TransactionStatus的实现源码:
public interface TransactionStatus extends SavepointManager, Flushable {
/**
* Return whether the present transaction is new (else participating
* in an existing transaction, or potentially not running in an
* actual transaction in the first place).
*/
boolean isNewTransaction();
/**
* Return whether this transaction internally carries a savepoint,
* that is, has been created as nested transaction based on a savepoint.
* This method is mainly here for diagnostic purposes, alongside
* {@link #isNewTransaction()}. For programmatic handling of custom
* savepoints, use SavepointManager's operations.
* @see #isNewTransaction()
* @see #createSavepoint
* @see #rollbackToSavepoint(Object)
* @see #releaseSavepoint(Object)
*/
boolean hasSavepoint();
/**
* Set the transaction rollback-only. This instructs the transaction manager
* that the only possible outcome of the transaction may be a rollback, as
* alternative to throwing an exception which would in turn trigger a rollback.
* This is mainly intended for transactions managed by
* {@link org.springframework.transaction.support.TransactionTemplate} or
* {@link org.springframework.transaction.interceptor.TransactionInterceptor},
* where the actual commit/rollback decision is made by the container.
* @see org.springframework.transaction.support.TransactionCallback#doInTransaction
* @see org.springframework.transaction.interceptor.TransactionAttribute#rollbackOn
*/
void setRollbackOnly();
/**
* Return whether the transaction has been marked as rollback-only
* (either by the application or by the transaction infrastructure).
*/
boolean isRollbackOnly();
/**
* Flush the underlying session to the datastore, if applicable:
* for example, all affected Hibernate/JPA sessions.
* This is effectively just a hint and may be a no-op if the underlying
* transaction manager does not have a flush concept. A flush signal may
* get applied to the primary resource or to transaction synchronizations,
* depending on the underlying resource.
*/
@Override
void flush();
/**
* Return whether this transaction is completed, that is,
* whether it has already been committed or rolled back.
* @see PlatformTransactionManager#commit
* @see PlatformTransactionManager#rollback
*/
boolean isCompleted();
}
事务隔离级别反映事务提交并发访问时的处理态度:
默认值是-1,没有超时限制。如果有,以秒为单位进行设置。
导入坐标
<packaging>jarpackaging>
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>5.0.2.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>5.0.2.RELEASEversion>
dependency>
<dependency>
<groupId>commons-dbutilsgroupId>
<artifactId>commons-dbutilsartifactId>
<version>1.4version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.20version>
dependency>
<dependency>
<groupId>c3p0groupId>
<artifactId>c3p0artifactId>
<version>0.9.1.2version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.8.7version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>5.0.2.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.2.0.RELEASEversion>
dependency>
dependencies>
创建实体类:
public class Account implements Serializable {
private int id;
private String name;
private Float money;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Float getMoney() {
return money;
}
public void setMoney(Float money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
持久层接口和接口的实现类:
public class IAccountImpl extends JdbcDaoSupport implements IAccountDao {
public List<Account> findAll() {
List<Account> accounts = getJdbcTemplate().query("select * from account",
new BeanPropertyRowMapper<Account>(Account.class));
return accounts;
}
public Account findByName(String name){
List<Account> accounts = super.getJdbcTemplate().query("select * from account where name = ?",
new BeanPropertyRowMapper<Account>(Account.class),name);
if(accounts.isEmpty()){
return null;
}
if(accounts.size()>1){
throw new RuntimeException("结果集不唯一");
}
return accounts.get(0);
}
public void updateAccount(Account account) {
getJdbcTemplate().update("update account set name=?,money=? where id=?",
account.getName(),account.getMoney(),account.getId());
}
}
业务层接口和接口的实现类:
public interface IAccountService {
List<Account> findAll();
void transfer(String sourceName, String targetName, Float money);
}
public class IAccountServiceImpl implements IAccountService {
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
public List<Account> findAll() {
try {
List<Account> accounts = accountDao.findAll();
return accounts;
}catch (Exception e){
throw new RuntimeException(e);
}
}
public void transfer(String sourceName, String targetName, Float money) {
try{
Account source = accountDao.findByName(sourceName);
Account target = accountDao.findByName(targetName);
source.setMoney(source.getMoney() - money);
target.setMoney(target.getMoney() + money);
accountDao.updateAccount(source);
accountDao.updateAccount(target);
} catch (Throwable t){
throw new RuntimeException(t);
}
}
}
创建bean.xml配置文件,导入约束:
<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="dyliang.service.impl.IAccountServiceImpl">
<property name="accountDao" ref="accountDao">property>
bean>
<bean id="accountDao" class="dyliang.dao.impl.IAccountImpl">
<property name="dataSource" ref="dataSource">property>
bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver">property>
<property name="url" value="jdbc:mysql://localhost:3306/sql_store?serverTimezone=GMT">property>
<property name="username" value="root">property>
<property name="password" value="1234">property>
bean>
<aop:config>
<aop:pointcut id="pt" expression="execution(* dyliang.service.impl.*.*(..))">aop:pointcut>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt">aop:advisor>
aop:config>
beans>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource">property>
bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">tx:advice>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<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:config>
<aop:pointcut id="pt" expression="execution(* dyliang.service.impl.*.*(..))">aop:pointcut>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt">aop:advisor>
aop:config>
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountTest {
@Autowired
private IAccountService as;
@Test
public void testTransfer(){
as.transfer("Forlogen","Kobe",100f);
}
}
事务控制主要在业务层,使用@Transactional配置事务管理。该注解的属性和xml中的属性含义一致。该注解可以出现在接口上,类上和方法上:
以上三个位置的优先级:方法 > 类 > 接口
@Service("accountService")
@Transactional(propagation= Propagation.SUPPORTS,readOnly=true)//只读型事务的配置
public class IAccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao;
@Override
public List<Account> findAll() {
try {
List<Account> accounts = accountDao.findAll();
return accounts;
}catch (Exception e){
throw new RuntimeException(e);
}
}
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
@Override
public void transfer(String sourceName, String targetName, Float money) {
try{
Account source = accountDao.findByName(sourceName);
Account target = accountDao.findByName(targetName);
source.setMoney(source.getMoney() - money);
target.setMoney(target.getMoney() + money);
accountDao.updateAccount(source);
accountDao.updateAccount(target);
} catch (Throwable t){
throw new RuntimeException(t);
}
}
}
如果完全不用xml配置文件,可以在主程序类上使用@EnableTransactionManagement开启事务管理