当前位置:   article > 正文

SpringBoot 配置多数据源(Sql Server、MySql)_springboot sqlserver

springboot sqlserver

当前实现多数据方式不够灵活,其他实现方式可以参考 SpringBoot + mybatis-plus 实现多数据源SpringBoot + mybatis-plus 实现多数据源。https://blog.csdn.net/qq_38080370/article/details/127514072 通过注解的方式来指定数据源,而不用通过目录的方式来控制。


创建SpringBoot项目就不说了。(直接使用IDEA创建就好了)

整个目录结构如图:(不用管图中报错,项目是在另一台电脑上写的。报错是没有jar包,因为网络比较慢。)

1、主要pom.xml

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-web</artifactId>
  5. </dependency>
  6. <!-- Spring Boot Test 依赖 -->
  7. <dependency>
  8. <groupId>org.springframework.boot</groupId>
  9. <artifactId>spring-boot-starter-test</artifactId>
  10. <scope>test</scope>
  11. </dependency>
  12. <!-- Spring Boot Mybatis 依赖 -->
  13. <dependency>
  14. <groupId>org.mybatis.spring.boot</groupId>
  15. <artifactId>mybatis-spring-boot-starter</artifactId>
  16. <version>1.2.0</version>
  17. </dependency>
  18. <!-- MySQL 连接驱动依赖 -->
  19. <dependency>
  20. <groupId>mysql</groupId>
  21. <artifactId>mysql-connector-java</artifactId>
  22. <version>${mysql-connector}</version>
  23. </dependency> <!-- Druid 数据连接池依赖 -->
  24. <dependency>
  25. <groupId>com.alibaba</groupId>
  26. <artifactId>druid</artifactId>
  27. <version>1.0.18</version>
  28. </dependency>
  29. <dependency>
  30. <groupId>junit</groupId>
  31. <artifactId>junit</artifactId>
  32. <version>3.8.1</version>
  33. <scope>test</scope>
  34. </dependency>
  35. <dependency>
  36. <groupId>com.microsoft.sqlserver</groupId>
  37. <artifactId>mssql-jdbc</artifactId>
  38. <version>7.0.0.jre8</version>
  39. </dependency>
  40. </dependencies>

2、在配置文件中配置多数据源application.properties

  1. ## 默认的数据源
  2. master.datasource.url=jdbc:mysql://localhost:3306/springbootdb?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true
  3. master.datasource.username=root
  4. master.datasource.password=admin
  5. master.datasource.driverClassName=com.mysql.jdbc.Driver
  6. ## 另一个的数据源
  7. cluster.datasource.url=jdbc:sqlserver://localhost:1433;DatabaseName=tablename
  8. cluster.datasource.username=sa
  9. cluster.datasource.password=admin
  10. cluster.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver

 我这配置SqlServer、MySql,如果需要连接MySql中的两个数据库。请自行更更改配置,并删除pom依赖。

3、配置mapper接口的数据源

MasterDataSourceConfig.java

  1. package com.wzq.datasource2.config;
  2. import javax.sql.DataSource;
  3. import com.alibaba.druid.pool.DruidDataSource;
  4. import org.apache.ibatis.session.SqlSessionFactory;
  5. import org.mybatis.spring.SqlSessionFactoryBean;
  6. import org.mybatis.spring.annotation.MapperScan;
  7. import org.springframework.beans.factory.annotation.Qualifier;
  8. import org.springframework.beans.factory.annotation.Value;
  9. import org.springframework.context.annotation.Bean;
  10. import org.springframework.context.annotation.Configuration;
  11. import org.springframework.context.annotation.Primary;
  12. import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
  13. import org.springframework.jdbc.datasource.DataSourceTransactionManager;
  14. @Configuration
  15. //扫描 Mapper 接口并容器管理
  16. @MapperScan(basePackages = {"com.wzq.datasource2.mapper.master"}, sqlSessionFactoryRef = "masterSqlSessionFactory")
  17. public class MasterDataSourceConfig {
  18. // 精确到 master 目录,以便跟其他数据源隔离
  19. static final String PACKAGE = "com.wzq.datasource2.mapper.master";
  20. static final String MAPPER_LOCATION = "classpath:mapper/master/*.xml";
  21. @Value("${master.datasource.url}")
  22. private String url;
  23. @Value("${master.datasource.username}")
  24. private String user;
  25. @Value("${master.datasource.password}")
  26. private String password;
  27. @Value("${master.datasource.driverClassName}")
  28. private String driverClass;
  29. @Primary
  30. @Bean(name = "masterDataSource")
  31. public DataSource masterDataSource() {
  32. DruidDataSource dataSource = new DruidDataSource();
  33. dataSource.setDriverClassName(driverClass);
  34. dataSource.setUrl(url);
  35. dataSource.setUsername(user);
  36. dataSource.setPassword(password);
  37. return dataSource;
  38. }
  39. @Bean(name = "masterTransactionManager")
  40. @Primary
  41. public DataSourceTransactionManager masterTransactionManager() {
  42. return new DataSourceTransactionManager(masterDataSource());
  43. }
  44. @Bean(name = "masterSqlSessionFactory")
  45. @Primary
  46. public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource masterDataSource)
  47. throws Exception {
  48. final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
  49. sessionFactory.setDataSource(masterDataSource);
  50. sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
  51. .getResources("classpath:mapper/master/*.xml"));
  52. return sessionFactory.getObject();
  53. }
  54. }

4、创建entity实体类

  1. public class StuT {
  2. private static final long serialVersionUID = 1L;
  3. private Integer id;
  4. private String name;
  5. //get/set
  6. }
  7. public class Stu {
  8. private static final long serialVersionUID = 1L;
  9. private Integer id;
  10. private String name;
  11. //get/set
  12. }
ClusterDataSourceConfig.java
  1. package com.wzq.datasource2.config;
  2. import javax.sql.DataSource;
  3. import org.apache.ibatis.session.SqlSessionFactory;
  4. import org.mybatis.spring.SqlSessionFactoryBean;
  5. import org.mybatis.spring.annotation.MapperScan;
  6. import org.springframework.beans.factory.annotation.Qualifier;
  7. import org.springframework.beans.factory.annotation.Value;
  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 com.alibaba.druid.pool.DruidDataSource;
  13. @Configuration
  14. //扫描 Mapper 接口并容器管理
  15. @MapperScan(basePackages = {"com.wzq.datasource2.mapper.cluster"}, sqlSessionFactoryRef = "clusterSqlSessionFactory")
  16. public class ClusterDataSourceConfig {
  17. // 精确到 cluster 目录,以便跟其他数据源隔离
  18. static final String PACKAGE = "com.wzq.datasource2.mapper.cluster";
  19. static final String MAPPER_LOCATION = "classpath:mapper/cluster/*.xml";
  20. @Value("${cluster.datasource.url}")
  21. private String url;
  22. @Value("${cluster.datasource.username}")
  23. private String user;
  24. @Value("${cluster.datasource.password}")
  25. private String password;
  26. @Value("${cluster.datasource.driverClassName}")
  27. private String driverClass;
  28. @Bean(name = "clusterDataSource")
  29. public DataSource clusterDataSource() {
  30. DruidDataSource dataSource = new DruidDataSource();
  31. dataSource.setDriverClassName(driverClass);
  32. dataSource.setUrl(url);
  33. dataSource.setUsername(user);
  34. dataSource.setPassword(password);
  35. return dataSource;
  36. }
  37. @Bean(name = "clusterTransactionManager")
  38. public DataSourceTransactionManager clusterTransactionManager() {
  39. return new DataSourceTransactionManager(clusterDataSource());
  40. }
  41. @Bean(name = "clusterSqlSessionFactory")
  42. public SqlSessionFactory clusterSqlSessionFactory(@Qualifier("clusterDataSource") DataSource clusterDataSource)
  43. throws Exception {
  44. final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
  45. sessionFactory.setDataSource(clusterDataSource);
  46. sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
  47. .getResources("classpath:mapper/cluster/*.xml"));
  48. return sessionFactory.getObject();
  49. }
  50. }

请根据实体类自行创建表 

5、编写mapper层

 

 

6、Service省略,目录结构如下:

 7、controller层

  1. package com.wzq.datasource2.controller;
  2. import com.wzq.datasource2.entity.cluster.StuT;
  3. import com.wzq.datasource2.entity.master.Stu;
  4. import com.wzq.datasource2.service.cluster.StuTService;
  5. import com.wzq.datasource2.service.master.StuService;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.beans.factory.annotation.Qualifier;
  8. import org.springframework.stereotype.Controller;
  9. import org.springframework.web.bind.annotation.RequestMapping;
  10. import org.springframework.web.bind.annotation.ResponseBody;
  11. import java.util.List;
  12. @Controller
  13. public class StuController {
  14. @Autowired
  15. @Qualifier(value = "stuServiceImpl")
  16. private StuService stuService;
  17. @Autowired
  18. @Qualifier(value = "stuTServiceImpl")
  19. private StuTService stuTService;
  20. @RequestMapping("/list")
  21. @ResponseBody
  22. public List<Stu> getAllStu(){
  23. return stuService.getAllStu();
  24. }
  25. @RequestMapping("/list2")
  26. @ResponseBody
  27. public List<StuT> getAllStuT(){
  28. return stuTService.getAllStuT();
  29. }
  30. }

总结:

1、配置多数据的目的是因为新项目需要用到老项目中的数据,而数据存放在两个不同的数据库当中,配置多数据源能很好的解决这一方面。还有一些公司进行了分库的操作,就比如一个指定增删改,一个指定查询。

2、 可能是我在配置数据源的时候使用了master或cluster,亦或者在配置mapper接口的数据源时指定的mastter或cluster,所以需要在mapperwen文件下创建master和cluster文件,以此来区分数据源的使用。

PS:报红是因为没有jar包!报红是因为没有jar包!报红是因为没有jar包!

GitHub网址:https://github.com/qz596766829/WzqRepository.git (datasoutrce2项目)

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

闽ICP备14008679号