当前位置:   article > 正文

Spring Boot + MyBatis + Druid环境下配置多数据源_mybatis. hana

mybatis. hana

项目中采用Spring Boot + MyBatis + Druid的架构,在原数据源的基础上需要添加一个新的数据源。

调试期间,发现添加了SqlSessionFactoryBean后,原数据源有一部分字段无法取值,后发现是application.yml中的配置失效,所以需要在SqlSessionFactoryBean中添加所需配置。

1. 在application.yml下配置两套数据源信息

默认数据源:

  1. spring:
  2. datasource:
  3. type: com.alibaba.druid.pool.DruidDataSource
  4. driverClassName: com.mysql.jdbc.Driver
  5. url: jdbc:mysql://192.168.1.10:3306/database1?useUnicode=true&characterEncoding=utf8
  6. username: root
  7. password: ****
  8. initialSize: 1
  9. minIdle: 3
  10. maxActive: 20
  11. # 配置获取连接等待超时的时间
  12. maxWait: 60000
  13. # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
  14. timeBetweenEvictionRunsMillis: 60000
  15. # 配置一个连接在池中最小生存的时间,单位是毫秒
  16. minEvictableIdleTimeMillis: 30000
  17. validationQuery: select 'x'
  18. testWhileIdle: true
  19. testOnBorrow: false
  20. testOnReturn: false

新增数据源

  1. hana:
  2. datasource:
  3. type: com.alibaba.druid.pool.DruidDataSource
  4. driverClassName: com.mysql.jdbc.Driver
  5. url: jdbc:mysql://192.168.6.12:3306/hana?useUnicode=true&characterEncoding=utf8
  6. username: root
  7. password: 1234
  8. initialSize: 1
  9. minIdle: 3
  10. maxActive: 20
  11. # 配置获取连接等待超时的时间
  12. maxWait: 60000
  13. # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
  14. timeBetweenEvictionRunsMillis: 60000
  15. # 配置一个连接在池中最小生存的时间,单位是毫秒
  16. minEvictableIdleTimeMillis: 30000
  17. validationQuery: select 'x'
  18. testWhileIdle: true
  19. testOnBorrow: false
  20. testOnReturn: false

2. 针对两个数据源分别写配置类DruidDBConfig.java 

要点:

a. basePackages 指定该数据源对应的MyBatis的Mapper类所在的包,表示指定包名下的数据库操作使用该数据源;

@MapperScan(basePackages = {"com.simba.*.dao"}, sqlSessionFactoryRef = "masterSqlSessionFactory ")

sqlSessionFactoryRef 指向了下面定义的bean

b. 定义一个masterSqlSessionFactory bean

如下代码指定了MyBatis的XML Mapping文件的路径和MapUnderscoreToCamelCase属性

  1. Resource[] resource = new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/**/*Mapper.xml");
  2. sqlSessionFactoryBean.setMapperLocations(resource);
  3. org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
  4. configuration.setMapUnderscoreToCamelCase(true);

它替代了原来application.yml中的配置,需注意的是,加了sqlSessionFactory bean 后,如下配置将不再生效,因此相关配置需在sqlSessionFactory 中完成。

  1. #[弃用]因为多数据源需要,MyBatis配置弃用,具体配置见DruidDBConfig
  2. #mybatis:
  3. # configuration:
  4. # map-underscore-to-camel-case: true
  5. # mapper-locations: mybatis/**/*Mapper.xml
  6. # typeAliasesPackage: com.simba.**.domain

 

默认数据源的配置Bean

  1. @Configuration
  2. @MapperScan(basePackages = {"com.simba.*.dao"}, sqlSessionFactoryRef = "masterSqlSessionFactory")//指定该数据源相应的MyBatis的Mapper类所在的包
  3. public class DruidDBConfig {
  4. private Logger logger = LoggerFactory.getLogger(DruidDBConfig.class);
  5. @Value("${spring.datasource.url}")
  6. private String dbUrl;
  7. @Value("${spring.datasource.username}")
  8. private String username;
  9. @Value("${spring.datasource.password}")
  10. private String password;
  11. @Value("${spring.datasource.driverClassName}")
  12. private String driverClassName;
  13. @Value("${spring.datasource.initialSize}")
  14. private int initialSize;
  15. @Value("${spring.datasource.minIdle}")
  16. private int minIdle;
  17. @Value("${spring.datasource.maxActive}")
  18. private int maxActive;
  19. @Value("${spring.datasource.maxWait}")
  20. private int maxWait;
  21. @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
  22. private int timeBetweenEvictionRunsMillis;
  23. @Value("${spring.datasource.minEvictableIdleTimeMillis}")
  24. private int minEvictableIdleTimeMillis;
  25. @Value("${spring.datasource.validationQuery}")
  26. private String validationQuery;
  27. @Value("${spring.datasource.testWhileIdle}")
  28. private boolean testWhileIdle;
  29. @Value("${spring.datasource.testOnBorrow}")
  30. private boolean testOnBorrow;
  31. @Value("${spring.datasource.testOnReturn}")
  32. private boolean testOnReturn;
  33. @Bean(initMethod = "init", destroyMethod = "close") //声明其为Bean实例
  34. @Primary //在同样的DataSource中,首先使用被标注的DataSource
  35. public DataSource dataSource() {
  36. DruidDataSource datasource = new DruidDataSource();
  37. datasource.setUrl(this.dbUrl);
  38. datasource.setUsername(username);
  39. datasource.setPassword(password);
  40. datasource.setDriverClassName(driverClassName);
  41. //configuration
  42. datasource.setInitialSize(initialSize);
  43. datasource.setMinIdle(minIdle);
  44. datasource.setMaxActive(maxActive);
  45. datasource.setMaxWait(maxWait);
  46. datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
  47. datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
  48. datasource.setValidationQuery(validationQuery);
  49. datasource.setTestWhileIdle(testWhileIdle);
  50. datasource.setTestOnBorrow(testOnBorrow);
  51. datasource.setTestOnReturn(testOnReturn);
  52. return datasource;
  53. }
  54. //创建Session
  55. @Bean(name="masterSqlSessionFactory")
  56. @Primary
  57. public SqlSessionFactory masterSqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception{
  58. final SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
  59. sqlSessionFactoryBean.setDataSource(dataSource);
  60. Resource[] resource = new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/**/*Mapper.xml");//MyBatis XML文件所在路径
  61. sqlSessionFactoryBean.setMapperLocations(resource);
  62. org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
  63. configuration.setMapUnderscoreToCamelCase(true);
  64. sqlSessionFactoryBean.setConfiguration(configuration);
  65. return sqlSessionFactoryBean.getObject();
  66. }
  67. }

新增数据源的配置bean

  1. @Configuration
  2. @MapperScan(basePackages = "com.hana.dao", sqlSessionFactoryRef = "hanaSqlSessionFactory")
  3. public class HanaDruidDBConfig {
  4. private Logger logger = LoggerFactory.getLogger(HanaDruidDBConfig.class);
  5. @Value("${hana.datasource.url}")
  6. private String dbUrl;
  7. @Value("${hana.datasource.username}")
  8. private String username;
  9. @Value("${hana.datasource.password}")
  10. private String password;
  11. @Value("${hana.datasource.driverClassName}")
  12. private String driverClassName;
  13. @Value("${hana.datasource.initialSize}")
  14. private int initialSize;
  15. @Value("${hana.datasource.minIdle}")
  16. private int minIdle;
  17. @Value("${hana.datasource.maxActive}")
  18. private int maxActive;
  19. @Value("${hana.datasource.maxWait}")
  20. private int maxWait;
  21. @Value("${hana.datasource.timeBetweenEvictionRunsMillis}")
  22. private int timeBetweenEvictionRunsMillis;
  23. @Value("${hana.datasource.minEvictableIdleTimeMillis}")
  24. private int minEvictableIdleTimeMillis;
  25. @Value("${hana.datasource.validationQuery}")
  26. private String validationQuery;
  27. @Value("${hana.datasource.testWhileIdle}")
  28. private boolean testWhileIdle;
  29. @Value("${hana.datasource.testOnBorrow}")
  30. private boolean testOnBorrow;
  31. @Value("${hana.datasource.testOnReturn}")
  32. private boolean testOnReturn;
  33. @Bean(initMethod = "init", destroyMethod = "close") //声明其为Bean实例
  34. public DataSource hanaDataSource() {
  35. DruidDataSource datasource = new DruidDataSource();
  36. datasource.setUrl(this.dbUrl);
  37. datasource.setUsername(username);
  38. datasource.setPassword(password);
  39. datasource.setDriverClassName(driverClassName);
  40. //configuration
  41. datasource.setInitialSize(initialSize);
  42. datasource.setMinIdle(minIdle);
  43. datasource.setMaxActive(maxActive);
  44. datasource.setMaxWait(maxWait);
  45. datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
  46. datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
  47. datasource.setValidationQuery(validationQuery);
  48. datasource.setTestWhileIdle(testWhileIdle);
  49. datasource.setTestOnBorrow(testOnBorrow);
  50. datasource.setTestOnReturn(testOnReturn);
  51. return datasource;
  52. }
  53. //创建Session
  54. @Bean(name="hanaSqlSessionFactory")
  55. public SqlSessionFactory hanaSqlSessionFactory(@Qualifier("hanaDataSource") DataSource hanaDataSource) throws Exception{
  56. final SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
  57. sqlSessionFactoryBean.setDataSource(hanaDataSource);
  58. /*Resource[] resource = new PathMatchingResourcePatternResolver().getResources(ClusterConfig.MAPPER_LOCATION);
  59. sqlSessionFactoryBean.setMapperLocations(resource);*/
  60. return sqlSessionFactoryBean.getObject();
  61. }
  62. }

这样就完成了配置,根据MapperScan中所指定的包名,自动选择相应数据源进行数据操作。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/691019
推荐阅读
相关标签
  

闽ICP备14008679号