本教程源碼請訪問:tutorial_demo 一、概述 之前我們學習了AOP,然後通過AOP對我們的Apache Commons DbUtils實現單表的CRUD操作的代碼添加了事務。Spring有其自己的事務控制的機制,我們完全可以在項目中使用Spring自己的事務控制機制。 JavaEE體系進行 ...
本教程源碼請訪問:tutorial_demo
一、概述
之前我們學習了AOP,然後通過AOP對我們的Apache Commons DbUtils實現單表的CRUD操作的代碼添加了事務。Spring有其自己的事務控制的機制,我們完全可以在項目中使用Spring自己的事務控制機制。
JavaEE體系進行分層開發,事務處理位於業務層,Spring提供了分層設計業務層的事務處理解決方案。
二、環境準備
我們之前學習了JdbcTemplate,我們的環境Dao層使用JdbcTemplate,後面三個部分的代碼,都在環境準備代碼基礎之上進行。
2.1、建庫建表
DROP DATABASE IF EXISTS springlearn;
CREATE DATABASE springlearn;
USE springlearn;
DROP TABLE IF EXISTS account;
CREATE TABLE account (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(40) DEFAULT NULL,
money float DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4;
INSERT INTO account VALUES ('1', 'aaa', '1000');
INSERT INTO account VALUES ('2', 'bbb', '1000');
INSERT INTO account VALUES ('3', 'ccc', '1000');
INSERT INTO account VALUES ('5', 'cc', '10000');
INSERT INTO account VALUES ('6', 'abc', '10000');
INSERT INTO account VALUES ('7', 'abc', '10000');
2.2、添加Account實體類
package org.codeaction.bean;
import java.io.Serializable;
public class Account implements Serializable {
private Integer id;
private String name;
private Float money;
public Integer getId() {
return id;
}
public void setId(Integer 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 +
'}';
}
}
2.3、添加Dao介面
package org.codeaction.dao;
import org.codeaction.bean.Account;
import java.util.List;
public interface IAccountDao {
Integer add(Account account);
Integer delete(Integer id);
Integer update(Account account);
List<Account> findAll();
Account findById(Integer id);
List<Account> findByName(String name);
Long count();
}
2.4、添加Dao介面實現類
package org.codeaction.dao.impl;
import org.codeaction.bean.Account;
import org.codeaction.dao.IAccountDao;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import java.util.List;
public class AccountDaoImpl implements IAccountDao {
private JdbcTemplate template;
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
@Override
public Integer add(Account account) {
Object[] args = {account.getName(), account.getMoney()};
return template.update("insert into account(name, money) values(?, ?)", args);
}
@Override
public Integer delete(Integer id) {
return template.update("delete from account where id=?", id);
}
@Override
public Integer update(Account account) {
Object[] args = {account.getName(), account.getMoney(), account.getId()};
return template.update("update account set name=?, money=? where id=?", args);
}
@Override
public List<Account> findAll() {
return template.query("select * from account",
new BeanPropertyRowMapper<Account>(Account.class));
}
@Override
public Account findById(Integer id) {
List<Account> list = template.query("select * from account where id=?",
new BeanPropertyRowMapper<Account>(Account.class), id);
return list.size() != 0 ? list.get(0) : null;
}
@Override
public List<Account> findByName(String name) {
return template.query("select * from account where name like ?",
new BeanPropertyRowMapper<Account>(Account.class), name);
}
@Override
public Long count() {
return template.queryForObject("select count(*) from account", Long.class);
}
}
2.5、添加Service介面
package org.codeaction.service;
public interface IAccountService {
void trans(Integer srcId, Integer dstId, Float money);
}
這裡只有一個轉賬操作,也是這個教程的關鍵。
2.6、添加Service介面實現類
package org.codeaction.service.impl;
import org.codeaction.bean.Account;
import org.codeaction.dao.IAccountDao;
import org.codeaction.service.IAccountService;
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public void trans(Integer srcId, Integer dstId, Float money) {
Account src = accountDao.findById(srcId);
Account dst = accountDao.findById(dstId);
if(src == null) {
throw new RuntimeException("轉出用戶不存在");
}
if(dst == null) {
throw new RuntimeException("轉入用戶不存在");
}
if(src.getMoney() < money) {
throw new RuntimeException("轉出賬戶餘額不足");
}
src.setMoney(src.getMoney() - money);
dst.setMoney(dst.getMoney() + money);
accountDao.update(src);
//int x = 1/0;
accountDao.update(dst);
}
}
2.7、添加Spring配置文件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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 配置AccountServiceImpl -->
<bean id="accountService" class="org.codeaction.service.impl.AccountServiceImpl">
<!-- 註入dao -->
<property name="accountDao" ref="accountDao"></property>
</bean>
<!-- 配置AccountDaoImpl -->
<bean id="accountDao" class="org.codeaction.dao.impl.AccountDaoImpl">
<!-- 註入jdbcTemplate -->
<property name="template" ref="template"></property>
</bean>
<!-- 配置JdbcTemplate -->
<bean id="template" class="org.springframework.jdbc.core.JdbcTemplate">
<!-- 註入數據源 -->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置數據源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 註入數據源屬性 -->
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/springlearn"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean>
</beans>
2.8、添加測試類
package org.codeaction.test;
import org.codeaction.service.IAccountService;
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;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:beans.xml")
public class MyTest {
@Autowired
private IAccountService accountService;
@Test
public void testTrans() {
accountService.trans(1, 2, 100F);
}
}
運行測試方法,能夠轉賬成功。如果在AccountServiceImpl的trans中添加int i = 1/0;
,轉賬失敗,但是沒有回滾,我們在下麵的代碼中添加事務控制。
三、基於XML的聲明式事務控制
基於XML的聲明式事務控制在上一節“環境準備”的基礎上進行。
3.1、修改Spring配置文件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
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">
<!-- 配置AccountServiceImpl -->
<bean id="accountService" class="org.codeaction.service.impl.AccountServiceImpl">
<!-- 註入dao -->
<property name="accountDao" ref="accountDao"></property>
</bean>
<!-- 配置AccountDaoImpl -->
<bean id="accountDao" class="org.codeaction.dao.impl.AccountDaoImpl">
<!-- 註入jdbcTemplate -->
<property name="template" ref="template"></property>
</bean>
<!-- 配置JdbcTemplate -->
<bean id="template" class="org.springframework.jdbc.core.JdbcTemplate">
<!-- 註入數據源 -->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置數據源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 註入數據源屬性 -->
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/springlearn"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!-- 配置事務管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 註入數據源 -->
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 配置事務的通知 -->
<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:attributes>
</tx:advice>
<!-- 配置AOP -->
<aop:config>
<!-- 配置切入點 -->
<aop:pointcut id="pt" expression="execution(* org.codeaction.service.impl.*.*(..))"></aop:pointcut>
<!-- 建立切入點表達式和事務通知的對應關係 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt"></aop:advisor>
</aop:config>
</beans>
Spring中基於XML的聲明式事務控制配置步驟:
- 配置事務管理器;
- 配置事務的通知;
- 配置AOP中通用切入點表達式;
- 建立切入點表達式和事務通知的對應關係;
- 配置事務的屬性。
事務的屬性如下:
- isolation:用於指定事務的隔離級別。預設值是DEFAULT,表示使用資料庫的預設隔離級別;
- propagation:用於指定事務的傳播行為。預設值是REQUIRED,表示一定會有事務,增刪改的選擇。查詢方法可以選擇SUPPORTS;
- read-only:用於指定事務是否只讀。只有查詢方法才能設置為true。預設值是false,表示讀寫;
- timeout:用於指定事務的超時時間,預設值是-1,表示永不超時。如果指定了數值,以秒為單位;
- rollback-for:用於指定一個異常,當產生該異常時,事務回滾,產生其他異常時,事務不回滾。沒有預設值。表示任何異常都回滾;
- no-rollback-for:用於指定一個異常,當產生該異常時,事務不回滾,產生其他異常時事務回滾。沒有預設值。表示任何異常都回滾。
3.2、測試
運行轉賬的測試方法,能夠正常轉賬,出現異常時,能夠正常回滾。
四、基於XML和註解的聲明式事務控制
4.1、修改Spring配置文件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="org.codeaction"></context:component-scan>
<!-- 配置JdbcTemplate -->
<bean id="template" class="org.springframework.jdbc.core.JdbcTemplate">
<!-- 註入數據源 -->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置數據源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 註入數據源屬性 -->
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/springlearn"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!-- 配置事務管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 註入數據源 -->
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 開啟Spring對註解事務的支持 -->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>
4.2、修改Dao介面的實現類
package org.codeaction.dao.impl;
import org.codeaction.bean.Account;
import org.codeaction.dao.IAccountDao;
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;
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
@Autowired
private JdbcTemplate template;
@Override
public Integer add(Account account) {
Object[] args = {account.getName(), account.getMoney()};
return template.update("insert into account(name, money) values(?, ?)", args);
}
@Override
public Integer delete(Integer id) {
return template.update("delete from account where id=?", id);
}
@Override
public Integer update(Account account) {
Object[] args = {account.getName(), account.getMoney(), account.getId()};
return template.update("update account set name=?, money=? where id=?", args);
}
@Override
public List<Account> findAll() {
return template.query("select * from account",
new BeanPropertyRowMapper<Account>(Account.class));
}
@Override
public Account findById(Integer id) {
List<Account> list = template.query("select * from account where id=?",
new BeanPropertyRowMapper<Account>(Account.class), id);
return list.size() != 0 ? list.get(0) : null;
}
@Override
public List<Account> findByName(String name) {
return template.query("select * from account where name like ?",
new BeanPropertyRowMapper<Account>(Account.class), name);
}
@Override
public Long count() {
return template.queryForObject("select count(*) from account", Long.class);
}
}
4.3、修改Service介面的實現類
package org.codeaction.service.impl;
import org.codeaction.bean.Account;
import org.codeaction.dao.IAccountDao;
import org.codeaction.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service("accountService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao;
@Override
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public void trans(Integer srcId, Integer dstId, Float money) {
Account src = accountDao.findById(srcId);
Account dst = accountDao.findById(dstId);
if(src == null) {
throw new RuntimeException("轉出用戶不存在");
}
if(dst == null) {
throw new RuntimeException("轉入用戶不存在");
}
if(src.getMoney() < money) {
throw new RuntimeException("轉出賬戶餘額不足");
}
src.setMoney(src.getMoney() - money);
dst.setMoney(dst.getMoney() + money);
accountDao.update(src);
//int x = 1/0;
accountDao.update(dst);
}
}
4.4、測試
運行轉賬的測試方法,能夠正常轉賬,出現異常時,能夠正常回滾。
五、基於純註解的聲明式事務控制
純註解配置就用不到XML配置文件了,我們在上一節的基礎上進行配置,刪除beans.xml。
5.1、修改Dao介面的實現類
package org.codeaction.dao.impl;
import org.codeaction.bean.Account;
import org.codeaction.dao.IAccountDao;
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;
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
@Autowired
private JdbcTemplate template;
@Override
public Integer add(Account account) {
Object[] args = {account.getName(), account.getMoney()};
return template.update("insert into account(name, money) values(?, ?)", args);
}
@Override
public Integer delete(Integer id) {
return template.update("delete from account where id=?", id);
}
@Override
public Integer update(Account account) {
Object[] args = {account.getName(), account.getMoney(), account.getId()};
return template.update("update account set name=?, money=? where id=?", args);
}
@Override
public List<Account> findAll() {
return template.query("select * from account",
new BeanPropertyRowMapper<Account>(Account.class));
}
@Override
public Account findById(Integer id) {
List<Account> list = template.query("select * from account where id=?",
new BeanPropertyRowMapper<Account>(Account.class), id);
return list.size() != 0 ? list.get(0) : null;
}
@Override
public List<Account> findByName(String name) {
return template.query("select * from account where name like ?",
new BeanPropertyRowMapper<Account>(Account.class), name);
}
@Override
public Long count() {
return template.queryForObject("select count(*) from account", Long.class);
}
}
5.2、修改Service介面的實現類
package org.codeaction.service.impl;
import org.codeaction.bean.Account;
import org.codeaction.dao.IAccountDao;
import org.codeaction.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service("accountService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao;
@Override
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public void trans(Integer srcId, Integer dstId, Float money) {
Account src = accountDao.findById(srcId);
Account dst = accountDao.findById(dstId);
if(src == null) {
throw new RuntimeException("轉出用戶不存在");
}
if(dst == null) {
throw new RuntimeException("轉入用戶不存在");
}
if(src.getMoney() < money) {
throw new RuntimeException("轉出賬戶餘額不足");
}
src.setMoney(src.getMoney() - money);
dst.setMoney(dst.getMoney() + money);
accountDao.update(src);
int x = 1/0;
accountDao.update(dst);
}
}
5.3、添加配置類及JDBC配置文件
5.3.1、添加JDBC配置文件
在resource目錄下,文件名:jdbc.properties
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springlearn
jdbc.username=root
jdbc.password=123456
5.3.2、添加JDBC配置類
package org.codeaction.config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;
public class JdbcConfig {
@Value("${jdbc.driverClass}")
private String driverClass;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean(name = "dataSource")
public DataSource dataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driverClass);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
return dataSource;
}
@Bean(name = "jdbcTemplate")
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
5.3.3、添加事務配置類
package org.codeaction.config;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
public class TransactionConfig {
@Bean("transactionManager")
public PlatformTransactionManager transactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
}
這個配置類用來創建事務管理器。
5.3.4、添加主配置類
package org.codeaction.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;
@Configuration
@ComponentScan(basePackages = "org.codeaction")
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class, TransactionConfig.class})
@EnableTransactionManagement
public class SpringConfig {
}
這個配置類做瞭如下幾件事:
- 聲明自己是一個配置類;
- 開啟包掃描,並配置要掃描的包;
- 引入JDBC配置文件;
- 引入另外的兩個配置類;
- 開啟Spring對註解事務的支持。
5.4、測試
運行轉賬的測試方法,能夠正常轉賬,出現異常時,能夠正常回滾。