spring基於xml配置事務
- 創建maven工程添加需要的依賴
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
- 編寫持久層dao和實現類接口 和實體類
package org.example.domain;
//實體類
public class Account {
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 +
'}';
}
}
package org.example.dao;
import org.example.domain.Account;
import java.io.Serializable;
public class Account implements Serializable {
/**
* 根據Id查詢賬戶
* @param accountId
* @return
*/
Account findAccountById(Integer accountId);
/**
* 根據名稱查詢賬戶
* @param accountName
* @return
*/
Account findAccountByName(String accountName);
/**
* 更新賬戶
* @param account
*/
void updateAccount(Account account);
}
package org.example.dao.impl;
import org.example.dao.IAccountDao;
import org.example.domain.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import java.util.List;
public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {
public Account findAccountById(Integer accountId) {
List<Account> accounts = super.getJdbcTemplate().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 = super.getJdbcTemplate().query("select * from account where name = ?",new BeanPropertyRowMapper<Account>(Account.class),accountName);
if(accounts.isEmpty()){
return null;
}
if(accounts.size()>1){
throw new RuntimeException("結果集不唯一");
}
return accounts.get(0);
}
public void updateAccount(Account account) {
super.getJdbcTemplate().update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}
}
- 編寫業務層service和實現類接口
package org.example.service;
import org.example.domain.Account;
public interface IAccountService {
/**
* 根據id查詢賬戶信息
* @param accountId
* @return
*/
Account findAccountById(Integer accountId);
/**
* 轉賬
* @param sourceName 轉成賬戶名稱
* @param targetName 轉入賬戶名稱
* @param money 轉賬金額
*/
void transfer(String sourceName,String targetName,Float money);
}
package org.example.service.impl;
import org.example.dao.IAccountDao;
import org.example.domain.Account;
import org.example.service.IAccountService;
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public Account findAccountById(Integer accountId) {
return accountDao.findAccountById(accountId);
}
@Override
public void transfer(String sourceName, String targetName, Float money) {
System.out.println("transfer....");
//2.1根據名稱查詢轉出賬戶
Account source = accountDao.findAccountByName(sourceName);
//2.2根據名稱查詢轉入賬戶
Account target = accountDao.findAccountByName(targetName);
//2.3轉出賬戶減錢
source.setMoney(source.getMoney()-money);
//2.4轉入賬戶加錢
target.setMoney(target.getMoney()+money);
//2.5更新轉出賬戶
accountDao.updateAccount(source);
//產生異常後測試是否會回滾事務
int i=1/0;
//2.6更新轉入賬戶
accountDao.updateAccount(target);
}
}
- 在bean.xml中導入約束配置持久層和業務層 配置spring事務
<?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="org.example.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
</bean>
<!-- 配置賬戶的持久層-->
<bean id="accountDao" class="org.example.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/student"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!-- spring中基於XML的聲明式事務控制配置步驟
1、配置事務管理器
2、配置事務的通知
此時我們需要導入事務的約束 tx名稱空間和約束,同時也需要aop的
使用tx:advice標籤配置事務通知
屬性:
id:給事務通知起一個唯一標識
transaction-manager:給事務通知提供一個事務管理器引用
3、配置AOP中的通用切入點表達式
4、建立事務通知和切入點表達式的對應關係
5、配置事務的屬性
是在事務的通知tx:advice標籤的內部
-->
<!-- 配置事務管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事務的通知-->
<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(* org.example.service.impl.*.*(..))"></aop:pointcut>
<!--建立切入點表達式和事務通知的對應關係 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
</aop:config>
</beans>
- 測試
package org.example;
import static org.junit.Assert.assertTrue;
import org.example.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:bean.xml")
public class AppTest
{
@Autowired
private IAccountService accountService;
@Test
public void testTransfer(){
accountService.transfer("aaa","bbb",100f);
}
}
產生異常數據庫值沒有變
spring基於註解配置事務
- 持久層代碼使用註解
package org.example.dao.impl;
import org.example.dao.IAccountDao;
import org.example.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;
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
@Autowired
private 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;
}
if(accounts.size()>1){
throw new RuntimeException("結果集不唯一");
}
return accounts.get(0);
}
public void updateAccount(Account account) {
jdbcTemplate.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}
}
- 業務層代碼使用@Transactional註解配置事務
package org.example.service.impl;
import org.example.dao.IAccountDao;
import org.example.domain.Account;
import org.example.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;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public Account findAccountById(Integer accountId) {
return accountDao.findAccountById(accountId);
}
//需要的是讀寫型事務配置
@Transactional(propagation= Propagation.REQUIRED,readOnly=false)
@Override
public void transfer(String sourceName, String targetName, Float money) {
System.out.println("transfer....");
//2.1根據名稱查詢轉出賬戶
Account source = accountDao.findAccountByName(sourceName);
//2.2根據名稱查詢轉入賬戶
Account target = accountDao.findAccountByName(targetName);
//2.3轉出賬戶減錢
source.setMoney(source.getMoney()-money);
//2.4轉入賬戶加錢
target.setMoney(target.getMoney()+money);
//2.5更新轉出賬戶
accountDao.updateAccount(source);
int i=1/0;
//2.6更新轉入賬戶
accountDao.updateAccount(target);
}
}
- 在配置文件中開啓對註解事務的支持
<?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.example"></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/student"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!-- spring中基於註解 的聲明式事務控制配置步驟
1、配置事務管理器
2、開啓spring對註解事務的支持
3、在需要事務支持的地方使用@Transactional註解
-->
<!-- 配置事務管理器 -->
<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>
</beans>