1. SpringBoot如何注解事务声明式事务
springboot的事务也主要分为两大类,
一是xml声明式事务,
二是注解事务,注解事务也可以实现类似声明式事务的方法,
springboot 之 xml事务
使用 @ImportResource("classpath:transaction.xml") 引入该xml的配置
springboot 注解事务
Transactional注解事务
注:需要在进行事物管理的方法上添加注解@Transactional,或者偷懒的话直接在类上面添加该注解
注解声明式事务
@Configuration
public class TxConfigBeanName {
@Autowired
private DataSourceTransactionManager transactionManager;
// 创建事务通知
@Bean(name = "txAdvice")
public TransactionInterceptor getAdvisor() throws Exception {
Properties properties = new Properties();
properties.setProperty("get*", "PROPAGATION_REQUIRED,-Exception,readOnly");
properties.setProperty("add*", "PROPAGATION_REQUIRED,-Exception,readOnly");
properties.setProperty("save*", "PROPAGATION_REQUIRED,-Exception,readOnly");
properties.setProperty("update*", "PROPAGATION_REQUIRED,-Exception,readOnly");
properties.setProperty("delete*", "PROPAGATION_REQUIRED,-Exception,readOnly");
TransactionInterceptor tsi = new TransactionInterceptor(transactionManager,properties);
return tsi;
}
@Bean
public BeanNameAutoProxyCreator txProxy() {
BeanNameAutoProxyCreator creator = new BeanNameAutoProxyCreator();
creator.setInterceptorNames("txAdvice");
creator.setBeanNames("*Service", "*ServiceImpl");
creator.setProxyTargetClass(true);
return creator;
}
}
2. Spring的声明式事务处理怎么配置,可以在提交事务后关闭数据库连接
try {
conn = u.getConnection();//连接数据库
//业务层的处理方法的调用。。。。。。
u.commit(conn);//提交
} catch (Exception e) {
u.rollback(conn);
} finally {
u.close(conn);//关闭
}