@Transactional注解异常报错之多数据源详解
短信预约 -IT技能 免费直播动态提醒
@Transactional注解报错之多数据源
如果在加上@Transactional注解之后报错,先查看程序是否为多数据源,之前专门有一章讲解springboot的多数据源实现。多数据源的情况下加事物注解,有可能会出现问题,以下是解决方案。
1.在配置数据源的同时
一定到在其中一个配置上加上@Primary注解,其他的不要加。
package com.wys.config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = "com.wys.mapper.**", sqlSessionFactoryRef = "oneSqlSessionFactory")
public class OneDataSourceConfig {
@Value("${spring.datasource.one.driver-class-name}")
String driverClass;
@Value("${spring.datasource.one.url}")
String url;
@Value("${spring.datasource.one.username}")
String userName;
@Value("${spring.datasource.one.password}")
String passWord;
@Primary
@Bean(name = "oneDataSource")
@ConfigurationProperties("spring.datasource.one")
public DataSource masterDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(driverClass);
dataSource.setUrl(url);
dataSource.setUsername(userName);
dataSource.setPassword(passWord);
return dataSource;
}
@Bean(name = "oneSqlSessionFactory")
public SqlSessionFactory sqlSessionFactory(@Qualifier("oneDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource);
sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath:mybatis/mapper-postgre
@Configuration
@MapperScan(basePackages = "com.wys.mapper.**", sqlSessionFactoryRef = "oneSqlSessionFactory")
public class OneDataSourceConfig {
@Value("${spring.datasource.one.driver-class-name}")
String driverClass;
@Value("${spring.datasource.one.url}")
String url;
@Value("${spring.datasource.one.username}")
String userName;
@Value("${spring.datasource.one.password}")
String passWord;
@Primary
@Bean(name = "oneDataSource")
@ConfigurationProperties("spring.datasource.one")
public DataSource masterDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(driverClass);
dataSource.setUrl(url);
dataSource.setUsername(userName);
dataSource.setPassword(passWord);
return dataSource;
}
@Bean(name = "oneSqlSessionFactory")
public SqlSessionFactory sqlSessionFactory(@Qualifier("oneDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource);
sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath:mybatis/mapper-postgre/*.xml"));
return sessionFactoryBean.getObject();
}
/
// 创建事务管理器1
@Bean(name = "oneManager1")
public PlatformTransactionManager txManager(@Qualifier("oneDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
/////////////////////////
@Bean(name = "oneSqlSessionFactory")
public SqlSessionTemplate sqlSessionFactoryTemplate(@Qualifier("oneSqlSessionFactory")SqlSessionFactory sqlSessionFactory ) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
在需要加注解的地方加上transactionManager 配置即可。
@Transactional(transactionManager ="oneManager1",rollbackFor=Exception.class)
@Transactional 错误使用的几种场景
@RestController
public class AController {
@Autowired
AService aService;
// 回滚
@GetMapping("direct")
public void direct() {
aService.testTransactional();
}
// 不回滚
@GetMapping("indirect")
public void indirect() {
aService.testTransactionalIndirect();
}
// 不回滚
@GetMapping("nonPublic")
public void nonPublic() {
aService.testTransactionalNonPublic();
}
// 不回滚
@GetMapping("catchException")
public void catchException() {
aService.testTransactionalCatchException();
}
// 不回滚
@GetMapping("sqlException")
public void sqlException() throws SQLException {
aService.testTransactionalSQLException();
}
// 回滚
@GetMapping("sqlExceptionWithRollbackfor")
public void sqlExceptionWithRollbackfor() throws SQLException {
aService.testTransactionalSQLExceptionWithRollbackfor();
}
}
@Service
public class AService {
@Autowired
TestTableDAO testTableDAO;
// 回滚
@Transactional
public void testTransactional() {
ATestTable er = new ATestTable();
er.setSummary("test");
testTableDAO.save(er);
throw new RuntimeException("exception");
}
// 不回滚: 类内部方法调用本类内部的其他方法并不会引起事务行为,即使被调用方法使用@Transactional注解进行修饰
public void testTransactionalIndirect() {
testTransactional();
}
// 不回滚: @Transaction注解只对方法名为pubic的才生效
@Transactional
void testTransactionalNonPublic() {
ATestTable er = new ATestTable();
er.setSummary("test");
testTableDAO.save(er);
throw new RuntimeException("exception");
}
// 不回滚
@Transactional
public void testTransactionalCatchException() {
ATestTable er = new ATestTable();
er.setSummary("test");
testTableDAO.save(er);
try {
throw new RuntimeException("exception");
} catch (Exception e) {
System.out.println("catch");
}
}
// 不回滚: @Transactional默认情况下只回滚RuntimeException和Error
@Transactional
public void testTransactionalSQLException() throws SQLException {
ATestTable er = new ATestTable();
er.setSummary("test");
testTableDAO.save(er);
throw new SQLException("exception");
}
// 回滚: 指定在 SQLException 异常发生时回滚
@Transactional(rollbackFor = {
SQLException.class
})
public void testTransactionalSQLExceptionWithRollbackfor() throws SQLException {
ATestTable er = new ATestTable();
er.setSummary("test");
testTableDAO.save(er);
throw new SQLException("exception");
}
}
@Repository
public interface TestTableDAO
extends JpaRepository<ATestTable, Integer>, JpaSpecificationExecutor<ATestTable> {
}
@Entity
@Data
@Table(name = "test")
public class ATestTable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
int id;
@Column(name = "summary", length = 512)
String summary;
}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341