@
目錄
- 聲明式
- 1. 基于XML的聲明式事務控制配置
- 1.1 maven導入
- 1.2 配置事務管理器
- 1.3 配置事務的屬性
- 1.4 bean.xml
- 2. 基于注解的聲明式事務控制配置
- 2.1 xml
- 2.2 業務層
- 2.3 持久層
- 3. 基于純注解的聲明式事務控制配置
- 3.1 config
- 3.2 JdbcConfig
- 3.3 TransactionConfig
- 1. 基于XML的聲明式事務控制配置
<packaging>jar</packaging>
<dependencies>
<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>8.0.23</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
- 配置事務管理器
-
配置事務的通知
此時我們需要導入事務的限制
名稱空間和限制,同時也需要tx
aop
的
使用
tx:advice
标簽配置事務通知
屬性:
:給事務通知起一個唯一辨別id
:給事務通知提供一個事務管理器引用transaction-manager
- 配置
中的通用切入點表達式AOP
- 建立事務通知和切入點表達式的對應關系
-
配置事務的屬性
是在事務的通知
标簽的内部tx:advice
-
:用于指定事務的隔離級别。預設值是isolation
,表示使用資料庫的預設隔離級别。DEFAULT
-
:用于指定事務的傳播行為。預設值是propagation
,表示一定會有事務,增删改的選擇。查詢方法可以選擇REQUIRED
。SUPPORTS
-
:用于指定事務是否隻讀。隻有查詢方法才能設定為read-only
。預設值是true
,表示讀寫。false
-
:用于指定事務的逾時時間,預設值是timeout
,表示永不逾時。如果指定了數值,以秒為機關。-1
-
:用于指定一個異常,當産生該異常時,事務復原,産生其他異常時,事務不復原。沒有預設值。表示任何異常都復原。rollback-for
-
:用于指定一個異常,當産生該異常時,事務不復原,産生其他異常時事務復原。沒有預設值。表示任何異常都復原。no-rollback-for
<?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="xyz.slienceme.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"/>
</bean>
<!-- 配置賬戶的持久層-->
<bean id="accountDao" class="xyz.slienceme.dao.impl.AccountDaoImpl">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 配置資料源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/eesy"/>
<property name="username" value="root"/>
<property name="password" value="**********"/>
</bean>
<!-- 配置事務管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</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:attributes>
</tx:advice>
<!-- 配置aop-->
<aop:config>
<!-- 配置切入點表達式-->
<aop:pointcut id="pt1" expression="execution(* xyz.slienceme.service.impl.*.*(..))"/>
<!--建立切入點表達式和事務通知的對應關系 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
</aop:config>
</beans>
<?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="xyz.slienceme"/>
<!-- 配置JdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 配置資料源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/eesy"/>
<property name="username" value="root"/>
<property name="password" value="***********"/>
</bean>
<!-- spring中基于注解 的聲明式事務控制配置步驟
1、配置事務管理器
2、開啟spring對注解事務的支援
3、在需要事務支援的地方使用@Transactional注解
-->
<!-- 配置事務管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 開啟spring對注解事務的支援-->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
package xyz.slienceme.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xyz.slienceme.dao.IAccountDao;
import xyz.slienceme.domain.Account;
import xyz.slienceme.service.IAccountService;
/**
* 賬戶的業務層實作類
*
* 事務控制應該都是在業務層
*/
@Service("accountService")
@Transactional
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao 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);
}
}
package xyz.slienceme.dao.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import xyz.slienceme.dao.IAccountDao;
import xyz.slienceme.domain.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import java.util.List;
/**
* 賬戶的持久層實作類
*/
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
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);
}
@Override
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);
}
@Override
public void updateAccount(Account account) {
jdbcTemplate.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}
}

package xyz.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的配置類,相當于bean.xml
*/
@Configuration //配置
@ComponentScan("xyz.slienceme") //設定掃描的包
@Import({JdbcConfig.class,TransactionConfig.class}) //導入相關配置
@PropertySource("classpath:jdbcConfig.properties") //配置檔案
@EnableTransactionManagement //開啟注解支援
public class SpringConfiguration {
}
package xyz.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;
/**
* 和連接配接資料庫相關的配置類
*/
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 ds = new DriverManagerDataSource();
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(username);
ds.setPassword(password);
return ds;
}
}
package xyz.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 {
/**
* 用于建立事務管理器對象
* @param dataSource
* @return
*/
@Bean(name="transactionManager")
public PlatformTransactionManager createTransactionManager(DataSource dataSource){
return new DataSourceTransactionManager(dataSource);
}
}