Spring5 进行事务管理
在Spring中对事务进行管理有两种方式:
(1)编程式:例如使用try-catch进行实现
(2)声明式:使用xml注解完成或使用纯注解方式实现
1-Spring注解声明式|配置事务管理器
1配置事务管理器
<bean id= "transactionManager"
class= "org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name= "dataSource" ref= "dataSource"></property>
</bean>
2配置文件,开启事务注解
<tx:annotation-driven transaction-manager= "transactionManager"></tx:annotation-driven>
3添加事务注解@Transactional,可以添加在类、方法上。
@Transactional中可以配置相关参数
- propagation:声明事务传播行为
- isolation:事物的隔离级别,处理脏读、不可重复读、幻读
- timeout
- readOnly
- rollbackFor…
2-Spring使用XML配置事务
1配置事务管理器,同上。
2配置通知
<!--2 配置通知-->
<tx:advice id= "txadvice">
<!--配置事务参数-->
<tx:attributes>
<!--指定哪种规则的方法上面添加事务,这个name需要是你的方法名称-->
<tx:method name= "accountMoney" propagation="REQUIRED"/>
<!--<tx:method name="account*"/>-->
</tx:attributes>
</tx:advice>
3配置切入面
<aop:config>
<!--配置切入点-->
<aop:pointcut id= "pt" expression="execution(*com.atguigu.spring5.service.UserService.*(..))"/>
<!--配置切面-->
<aop:advisor advice-ref="txadvice" pointcut-ref="pt"/>
</aop:config>
3-Spring 使用配置类进行纯注解开发
package shiwu.config;
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;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.sql.DataSource;
@Configuration // 声明是配置类
@ComponentScan(basePackages = "shiwu") // 组件扫描
@EnableTransactionManagement // 开启事务
public class Config {
@Bean // 返回数据库
public DruidDataSource getDruidDataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUsername("root");
dataSource.setPassword("123456");
dataSource.setUrl("jdbc:mysql:///book?useUnicode=true&characterEncoding=utf8");
return dataSource;
}
@Bean // 数据库模板中注入数据库
public JdbcTemplate getJdbcTemplate(DataSource dataSource){
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource);
return jdbcTemplate;
}
@Bean // 事务管理器获得
public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource){
DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSource);
return dataSourceTransactionManager;
}
}
… 这就没有了…我还能接着讲…