JAVA全系列 教程
3762个小节阅读:7091.9k
目录
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
Spring支持使用注解配置声明式事务。用法如下:
注册事务注解驱动
xxxxxxxxxx
<!-- 注册事务注解驱动 -->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
在需要事务支持的方法或类上加@Transactional
xxxxxxxxxx
@Service
// 作用于类上时,该类的所有public方法将都具有该类型的事务属性
@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT)
public class AccountService {
@Autowired
private AccountDao accountDao;
/**
* 转账
* @param id1 转出人id
* @param id2 转入人id
* @param price 金额
*/
// 作用于方法上时,该方法将都具有该类型的事务属性
@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT)
public void transfer(int id1, int id2, double price) {
// account1修改余额
Account account1 = accountDao.findById(id1);
account1.setBalance(account1.getBalance()-price);
accountDao.update(account1);
int i = 1/0; // 模拟转账出错
// account2修改余额
Account account2 = accountDao.findById(id2);
account2.setBalance(account2.getBalance()+price);
accountDao.update(account2);
}
}
配置类代替xml中的注解事务支持:在配置类上方写@EnableTranscationManagement
xxxxxxxxxx
@Configuration
@ComponentScan("com.itbaizhan")
@EnableTransactionManagement
public class SpringConfig {
@Bean
public DataSource getDataSource(){
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");
druidDataSource.setUrl("jdbc:mysql:///spring");
druidDataSource.setUsername("root");
druidDataSource.setPassword("root");
return druidDataSource;
}
@Bean
public SqlSessionFactoryBean getSqlSession(DataSource dataSource){
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
return sqlSessionFactoryBean;
}
@Bean
public MapperScannerConfigurer getMapperScanner(){
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage("com.itbaizhan.dao");
return mapperScannerConfigurer;
}
@Bean
public DataSourceTransactionManager getTransactionManager(DataSource dataSource){
DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSource);
return dataSourceTransactionManager;
}
}
1.在Spring中,配置声明式事务用到的注解为
A @Configuration
B @Import
C @Transactional
D @Service
答案
1=>C