springboot+mybatis实现多数据源

1.springboot+mybatis实现多数据源后,针对单个数据源我们可以使用@Transactional(name="xxxTransactionManager")

来指定使用的事务管理器,但是如果被注解的方法需要同时支持两个事务管理器呢,这个时候如果用@Transactional注解就不

合适了,属性name只支持字符串类型,所以只能填一个,如果不传name属性,而且项目没有配置默认的事务管理器,在调用方

法时则会抛出未指定默认事务管理器的异常。这个时候,我们可以用编程式事务来解决这个问题。

2.多数据源配置已经完成,但是还没有事务管理器,所以先配置支持事务。

 
  
  1. import org.apache.ibatis.session.SqlSessionFactory;

  2. import org.mybatis.spring.SqlSessionFactoryBean;

  3. import org.mybatis.spring.SqlSessionTemplate;

  4. import org.mybatis.spring.annotation.MapperScan;

  5. import org.springframework.beans.factory.annotation.Qualifier;

  6. import org.springframework.boot.context.properties.ConfigurationProperties;

  7. import org.springframework.boot.jdbc.DataSourceBuilder;

  8. import org.springframework.context.annotation.Bean;

  9. import org.springframework.context.annotation.Configuration;

  10. import org.springframework.context.annotation.Primary;

  11. import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

  12. import org.springframework.jdbc.datasource.DataSourceTransactionManager;

  13. import org.springframework.transaction.PlatformTransactionManager;

  14. import javax.sql.DataSource;

  15. /**

  16. * 数据源1

  17. */

  18. @Configuration

  19. @MapperScan(basePackages = "com.example.mybatis.mapper",sqlSessionFactoryRef = "sqlSessionFactoryOne")

  20. public class DataSourceConfigOne {

  21. @Bean(name = "dataSourceOne")

  22. @Primary// 表示这个数据源是默认数据源

  23. // 读取application.properties中的配置参数映射成为一个对象,prefix表示参数的前缀

  24. @ConfigurationProperties(prefix = "spring.datasource.one")

  25. public DataSource dataSourceOne() {

  26. return DataSourceBuilder.create().build();

  27. }

  28. @Bean(name = "sqlSessionFactoryOne")

  29. @Primary

  30. public SqlSessionFactory sqlSessionFactoryOne(@Qualifier("dataSourceOne") DataSource datasource)throws Exception {

  31. SqlSessionFactoryBean bean = new SqlSessionFactoryBean();

  32. bean.setDataSource(datasource);

  33. bean.setMapperLocations(

  34. // 设置mybatis的xml所在位置

  35. new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));

  36. bean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);

  37. return bean.getObject();

  38. }

  39. @Bean(name = "transactionManagerOne")

  40. public PlatformTransactionManager transactionManagerOne(@Qualifier("dataSourceOne") DataSource dataSourceOne) {

  41. return new DataSourceTransactionManager(dataSourceOne);

  42. }

  43. @Primary

  44. public SqlSessionTemplate sqlsessiontemplateOne(@Qualifier("sqlsessiontemplateOne") SqlSessionFactory sessionfactory) {

  45. return new SqlSessionTemplate(sessionfactory);

  46. }

  47. }

 
  
  1. import org.apache.ibatis.session.SqlSessionFactory;

  2. import org.mybatis.spring.SqlSessionFactoryBean;

  3. import org.mybatis.spring.SqlSessionTemplate;

  4. import org.mybatis.spring.annotation.MapperScan;

  5. import org.springframework.beans.factory.annotation.Qualifier;

  6. import org.springframework.boot.context.properties.ConfigurationProperties;

  7. import org.springframework.boot.jdbc.DataSourceBuilder;

  8. import org.springframework.context.annotation.Bean;

  9. import org.springframework.context.annotation.Configuration;

  10. import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

  11. import org.springframework.jdbc.datasource.DataSourceTransactionManager;

  12. import org.springframework.transaction.PlatformTransactionManager;

  13. import javax.sql.DataSource;

  14. /**

  15. * 数据源2

  16. */

  17. @Configuration

  18. @MapperScan(basePackages = "com.example.mybatis.mapper2",sqlSessionFactoryRef = "sqlSessionFactoryTwo")

  19. public class DataSourceConfigTwo {

  20. @Bean(name = "dataSourceTwo")

  21. // 读取application.properties中的配置参数映射成为一个对象,prefix表示参数的前缀

  22. @ConfigurationProperties(prefix = "spring.datasource.two")

  23. public DataSource dataSourceTwo() {

  24. return DataSourceBuilder.create().build();

  25. }

  26. @Bean(name = "sqlSessionFactoryTwo")

  27. public SqlSessionFactory sqlSessionFactoryTwo(@Qualifier("dataSourceTwo") DataSource datasource)throws Exception {

  28. SqlSessionFactoryBean bean = new SqlSessionFactoryBean();

  29. bean.setDataSource(datasource);

  30. bean.setMapperLocations(

  31. // 设置mybatis的xml所在位置

  32. new PathMatchingResourcePatternResolver().getResources("classpath:mapper2/*.xml"));

  33. bean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);//下划线-驼峰映射

  34. return bean.getObject();

  35. }

  36. @Bean(name = "transactionManagerTwo")

  37. public PlatformTransactionManager transactionManagerTwo(@Qualifier("dataSourceTwo") DataSource dataSourceTwo) {

  38. return new DataSourceTransactionManager(dataSourceTwo);

  39. }

  40. public SqlSessionTemplate sqlsessiontemplateTwo(@Qualifier("sqlsessiontemplateTwo") SqlSessionFactory sessionfactory) {

  41. return new SqlSessionTemplate(sessionfactory);

  42. }

  43. }

3.使用自定义注解

 
  
  1. @Retention(RetentionPolicy.RUNTIME)

  2. @Target({ElementType.METHOD,ElementType.PARAMETER})

  3. public @interface MoreTransaction {

  4. String[] value() default {};

  5. }

4.事务切面

 
  
  1. @Aspect

  2. @Component

  3. public class TransactionAop {

  4. @Pointcut("@annotation(com.example.mybatis.config.aop.annotation.MoreTransaction)")

  5. public void MoreTransaction() {

  6. }

  7. @Pointcut("execution(* com.example.mybatis.controller.*.*(..))")

  8. public void excudeController() {

  9. }

  10. @Around(value = "MoreTransaction()&&excudeController()&&@annotation(annotation)")

  11. public Object twiceAsOld(ProceedingJoinPoint thisJoinPoint, MoreTransaction annotation) throws Throwable {

  12. Stack dataSourceTransactionManagerStack = new Stack<>();

  13. Stack transactionStatuStack = new Stack<>();

  14. try {

  15. if (!openTransaction(dataSourceTransactionManagerStack, transactionStatuStack, annotation)) {

  16. return null;

  17. }

  18. Object ret = thisJoinPoint.proceed();

  19. commit(dataSourceTransactionManagerStack, transactionStatuStack);

  20. return ret;

  21. } catch (Throwable e) {

  22. rollback(dataSourceTransactionManagerStack, transactionStatuStack);

  23. log.error(String.format("MultiTransactionalAspect, method:%s-%s occors error:",

  24. thisJoinPoint.getTarget().getClass().getSimpleName(), thisJoinPoint.getSignature().getName()), e);

  25. throw e;

  26. }

  27. }

  28. /**

  29. * 开启事务处理方法

  30. *

  31. * @param dataSourceTransactionManagerStack

  32. * @param transactionStatuStack

  33. * @param multiTransactional

  34. * @return

  35. */

  36. private boolean openTransaction(Stack dataSourceTransactionManagerStack,

  37. Stack transactionStatuStack,MoreTransaction multiTransactional) {

  38. String[] transactionMangerNames = multiTransactional.value();

  39. if (ArrayUtils.isEmpty(multiTransactional.value())) {

  40. return false;

  41. }

  42. for (String beanName : transactionMangerNames) {

  43. DataSourceTransactionManager dataSourceTransactionManager =(DataSourceTransactionManager) SpringContextUtil.getBean(beanName);

  44. TransactionStatus transactionStatus = dataSourceTransactionManager

  45. .getTransaction(new DefaultTransactionDefinition());

  46. transactionStatuStack.push(transactionStatus);

  47. dataSourceTransactionManagerStack.push(dataSourceTransactionManager);

  48. }

  49. return true;

  50. }

  51. /**

  52. * 提交处理方法

  53. *

  54. * @param dataSourceTransactionManagerStack

  55. * @param transactionStatuStack

  56. */

  57. private void commit(Stack dataSourceTransactionManagerStack,

  58. Stack transactionStatuStack) {

  59. while (!dataSourceTransactionManagerStack.isEmpty()) {

  60. dataSourceTransactionManagerStack.pop().commit(transactionStatuStack.pop());

  61. }

  62. }

  63. /**

  64. * 回滚处理方法

  65. * @param dataSourceTransactionManagerStack

  66. * @param transactionStatuStack

  67. */

  68. private void rollback(Stack dataSourceTransactionManagerStack,

  69. Stack transactionStatuStack) {

  70. while (!dataSourceTransactionManagerStack.isEmpty()) {

  71. dataSourceTransactionManagerStack.pop().rollback(transactionStatuStack.pop());

  72. }

  73. }

  74. }

5.service层两个我要新增的方法,这两个方法是两个数据源(一个是我本地的,一个是阿里云的)

 
  
  1. @Override

  2. public int addUserInfo(UserInfo record) {

  3. return userInfoMapper.insert(new UserInfo().setId(UUID.randomUUID().toString()).setUserAccount("吾问无为谓"));

  4. }

 
  
  1. @Override

  2. public int addUser(User record) {

  3. return userMapper.insertSelective(record);

  4. }

 6.controller层的调用方法上使用事务注解,将两个数据源的事务管理器名字作为参数传入。

 
  
  1. @GetMapping("/dataSourceList")

  2. @ResponseBody

  3. @MoreTransaction(value = {"transactionManagerOne","transactionManagerTwo"})

  4. public ResultData getDataSourceList(){

  5. int i=userService.addUser(new User().setPhone("11111111111").setUserName("哈哈哈"));

  6. int a=1/0;

  7. int k=userService.addUserInfo(new UserInfo().setId(UUID.randomUUID().toString()).setUserAccount("吾问无为谓"));

  8. Map map=new HashMap();

  9. map.put("k",k);

  10. return ResultData.success(map);

  11. }

7.提交请求后会发现控制台报错,但是数据库里面并没有插入数据。

文章知识点与官方知识档案匹配,可进一步学习相关知识

你可能感兴趣的:(mybatis,spring,boot,java)