目录
编程式事务
通过TransactionTemplate或TransactionManager手动管理事务,应为是手动,所以实际开发中很少使用。但便于理解Spring事务管理原理,建议新手先学习编程式事务。
我们通过一个案例去理解Spring中的事务,在数据库account中有zhangsan和lisi两个人,现在用编程式事务的方式实现转账功能。
首先在pom.xml文件中添加依赖spring-context + spring-jdbc + druid + mysql-connector-java + junit(用于测试)
<?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>org.example</groupId>
<artifactId>tx</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.18</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.18</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.9</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.27</version>
</dependency>
</dependencies>
</project>
package com.qfedu.demo.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
/**
* 操作类
*/
@Repository
public class AccountDao {
@Autowired
JdbcTemplate jdbcTemplate;
/**
* 向指定用户的余额中添加指定额度
* @param username 指定用户
* @param money 添加多少金额
*/
public void addMoney(String username, Double money) {
jdbcTemplate.update("update account set money=money+? where username=?;", money, username);
}
/**
* 向指定用户夫人余额减少额度
* @param username 指定用户
* @param money 较少多少金额
*/
public void minusMoney(String username, Double money) {
jdbcTemplate.update("update account set money=money-? where username=?;", money, username);
}
}
使用TransactionTamplate
package com.qfedu.demo.service;
import com.qfedu.demo.dao.AccountDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
/**
* 服务类
*/
@Service
public class AccountService {
@Autowired
protected AccountDao accountDao;
@Autowired
private TransactionTemplate transactionTemplate;
/**
* 转账方法
* @param from 金额减少的用户
* @param to 金额增加的用户
* @param money 转账的金额
*/
public void transferMoney(String from, String to, Double money) {
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
try {
accountDao.minusMoney(from, money);
accountDao.addMoney(to, money);
} catch (Exception e) {
e.printStackTrace();
//回滚
status.setRollbackOnly();
}
}
});
}
}
使用TransactionManager
TransactionManager是一个接口,并且是空接口。所以在具体的代码中,要用其的子类PlatformTransactionManager,在这个子类有且仅有三个方法,对应的功能分别是开启事务、提交事务和回滚事务。虽然在AccountService中使用的是PlatformTransactionManager,但是在applicationContext.xml配置文件中使用的是DataSourceTransactionManager。这利用的是泛型的知识。
package com.qfedu.demo.service;
import com.qfedu.demo.dao.AccountDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
@Service
public class AccountService01 {
@Autowired
private AccountDao accountDao;
@Autowired
private PlatformTransactionManager platformTransactionManager;
public void TransferMoney(String from, String to, Double money) {
DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
//开启事务
TransactionStatus status = platformTransactionManager.getTransaction(definition);
try {
accountDao.minusMoney(from, money);
accountDao.addMoney(to, money);
platformTransactionManager.commit(status);
} catch (Exception e) {
e.printStackTrace();
platformTransactionManager.rollback(status);
}
}
}
applicationContext.xml配置文件,如果是使用TransactionManager,可以不用配置TransactionTemplate。
<?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 https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.qfedu.demo"/>
<context:property-placeholder location="classpath:db.properties"/>
<bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
<property name="username" value="root"/>
<property name="password" value="123456"/>
<property name="url" value="jdbc:mysql:///jdbc01"/>
</bean>
<bean class="org.springframework.jdbc.core.JdbcTemplate" id="jdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 创建一个,MySQL数据库的事务管理器-->
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean class="org.springframework.transaction.support.TransactionTemplate" id="transactionTemplate">
<property name="transactionManager" ref="transactionManager"/>
</bean>
</beans>
package com.qfedu.demo.service;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* 测试类
*/
public class AccountTest01 {
private ClassPathXmlApplicationContext ctx;
@Before
public void before() {
ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
}
/**
* 使用TransactionTemplate
*/
@Test
public void testTransactionManager() {
AccountService accountService = ctx.getBean(AccountService.class);
accountService.transferMoney("zhangsan", "lisi", 50.0);
}
/**
* 使用TransactionManager
*/
@Test
public void testTransactionTemplate() {
AccountService01 accountService01 = ctx.getBean(AccountService01.class);
accountService01.TransferMoney("zhangsan","lisi",50.0);
}
}
其实不管是使用TransactionManager,还是使用TransactionTemplate,都差不多。在实际开发中,主要是使用声明式事务, 因为声明式事务代码入侵少,其本质式通过AOP实现。
声明式事务
XML文件配置
首先在pom.xml配置文件中添加依赖,除了编程式事务的依赖外,因为使用了AOP,所以还需要aspectjrt 和 aspectjweaver
<?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>org.example</groupId>
<artifactId>tx02</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.18</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.18</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.9</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.27</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.9.1</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.9.1</version>
</dependency>
</dependencies>
</project>
操作类AccountDao与编程式事务的AccoutDao一样,这里不再赘叙。
相比于编程式事务,声明式事务的AccountService显得极为简介,写上自己的业务就可以了,这是由于使用了AOP,那些相同的代码提前做好了。
package com.qfedu.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class AccountService {
@Autowired
private AccountDao accountDao;
public void transferMoney(String from, String to, Double money) {
accountDao.minusMoney(from, money);
accountDao.addMoney(to, money);
}
}
声明式的 applicationContext.xml 配置文件主要分为五个步骤:配置数据源、配置JdbcTemplate、配置事务管理器、配置事务属性和配置AOP。
<?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:tx="http://www.springframework.org/schema/tx"
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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="com.qfedu.demo"/>
<!--
配置数据源
-->
<bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
<property name="url" value="jdbc:mysql:///jdbc01"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!--
配置jdbcTemplate
-->
<bean class="org.springframework.jdbc.core.JdbcTemplate" id="jdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--
配置事务管理器
-->
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--
配置事务属性
-->
<tx:advice id="transactionInterceptor">
<tx:attributes>
<!-- 给方法添加事务-->
<tx:method name="transferMoney"/>
</tx:attributes>
</tx:advice>
<!--
配置AOP
-->
<aop:config>
<!--配置切点-->
<aop:pointcut id="pc01" expression="execution(* com.qfedu.demo.AccountService.*(..))"/>
<aop:advisor advice-ref="transactionInterceptor" pointcut-ref="pc01"/>
</aop:config>
</beans>
package com.qfedu.demo;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* 测试类
*/
class AccountServiceTest01 {
public static void main(String[] args) {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
AccountService accountService = ctx.getBean(AccountService.class);
accountService.transferMoney("zhangsan", "lisi", 50.0);
}
}
因为声明式事务的简洁,所以在实际开发中,一般都是使用声明式事务。
java代码配置
配置类
package com.qfedu.demo01;
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;
/**
* 配置类
*/
@Configuration
@ComponentScan
//开启事务注解,通过注解标记事务
@EnableTransactionManagement
public class JavaConfig {
@Bean
DruidDataSource dataSource() {
DruidDataSource ds = new DruidDataSource();
ds.setUrl("jdbc:mysql:///jdbc01");
ds.setUsername("root");
ds.setPassword("123456");
return ds;
}
@Bean
JdbcTemplate jdbcTemplate() {
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource());
return jdbcTemplate;
}
@Bean
DataSourceTransactionManager transactionManager() {
DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
transactionManager.setDataSource(dataSource());
return transactionManager;
}
}
其实就是把applicationContext.xml配置文件翻译程java代码,但是配置事务属性 和 配置AOP需要注意,applicationContext.xml中的配置事务属性对应Java代码配置@EnableTransactionManager,表示开始事务注解,之后再AccountService#transferMoney添加注解@transactioal,表示为方法添加事务。
package com.qfedu.demo01;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* 服务类
*/
@Service
public class AccountService {
@Autowired
private AccountDao accountDao;
//表示给方法添加事务,该注解如果在类上,则表示为该类的所有方法添加事务
@Transactional
public void transferMoney(String from, String to, Double money) {
accountDao.minusMoney(from, money);
accountDao.addMoney(to, money);
}
}
package com.qfedu.demo01;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* 测试类
*/
class JavaConfigTest01 {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(JavaConfig.class);
AccountService accountService = ctx.getBean(AccountService.class);
accountService.transferMoney("zhangsan", "lisi", 50.0);
}
}
总结:建议使用声明式事务,用XML配置还是Java代码配置就得看个人喜欢了。其实本人还是喜欢用XMl配置的。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/14613.html