当前位置:   article > 正文

SpringBoot 2.7教程:SpringBoot 整合 mybatis 多数据源连接方法-2022年最新图文版本_springboot2.7.10对应driverclassname

springboot2.7.10对应driverclassname

SpringBoot 2.7教程:SpringBoot + Web 项目搭建及实践应用-2022年最新图文版本

SpringBoot 2.7教程:SpringBoot + Web 项目搭建,异常捕获处理-2022年最新图文版本

SpringBoot 2.7教程:SpringBoot + Mysql 项目应用-2022年最新图文版本

SpringBoot 2.7教程:SpringBoot 集成 jsp 页面开发 -2022年最新图文版本

SpringBoot 2.7教程:SpringBoot 实现文件上传,图片上传并显示功能-2022年最新图文版本

SpringBoot 2.7教程:springboot 设置全局字符编码,解决乱码问题-2022年最新图文版

SpringBoot 2.7教程:SpringBoot mybatis 多数据源的整合方法-2022年最新图文版本

SpringBoot 2.7教程:SpringBoot 整合 RocketMQ 项目搭建-2022年最新图文版本

SpringBoot 2.7教程:SpringBoot 整合 RabbitMQ 项目搭建-2022年最新图文版本

SpringBoot 2.7教程:SpringBoot 整合 MongoDB 项目搭建-2022年最新图文版本

SpringBoot 2.7教程:SpringBoot 整合 Redisson 项目搭建-2022年最新图文版本

SpringBoot 2.7教程:SpringBoot 整合 Redis 项目搭建-2022年最新图文版本

本章学习目标:

学习 springboot-mybatis 多数据源的整合方法

项目开发过程中会遇到单个项目要连接过个数据库实例的情况,如业务需要访问 用户库 和订单库。

目录

一、项目mybatis-muilt-database最终项目结构

二、配置pom.xml文件

三、配置properties

四、配置数据源类

五、书写mapper  and  xml

六、书写service

七、书写controller

八、Mysql 数据库文件

九、测试


当前最常用的版本2.2.x、2.3.x将在2022年停止维护了。

下面我们以最新的版本2.7进行系统搭建。

一、项目mybatis-muilt-database最终项目结构

二、配置pom.xml文件

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-web</artifactId>
  5. <version>2.7.0</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.mybatis.spring.boot</groupId>
  9. <artifactId>mybatis-spring-boot-starter</artifactId>
  10. <version>2.1.4</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>mysql</groupId>
  14. <artifactId>mysql-connector-java</artifactId>
  15. <version>8.0.29</version>
  16. </dependency>
  17. <!-- Druid 数据连接池依赖 -->
  18. <dependency>
  19. <groupId>com.alibaba</groupId>
  20. <artifactId>druid</artifactId>
  21. <version>1.1.8</version>
  22. </dependency>
  23. <dependency>
  24. <groupId>log4j</groupId>
  25. <artifactId>log4j</artifactId>
  26. <version>1.2.16</version>
  27. <scope>compile</scope>
  28. </dependency>
  29. </dependencies>

三、配置properties

  1. # 应用名称
  2. spring.application.name=mybatis-multi-datasource
  3. # 应用服务 WEB 访问端口
  4. server.port=8080
  5. datasource.user.url=jdbc:mysql://mysql_host:3306/user?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true
  6. datasource.user.username=root
  7. datasource.user.password=password
  8. datasource.user.driverClassName=com.mysql.cj.jdbc.Driver
  9. datasource.order.url=jdbc:mysql://mysql_host:3306/order?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true
  10. datasource.order.username=root
  11. datasource.order.password=password
  12. datasource.order.driverClassName=com.mysql.cj.jdbc.Driver
  13. # 连接池的配置信息
  14. # 初始化大小,最小,最大
  15. spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
  16. spring.datasource.initialSize=5
  17. spring.datasource.minIdle=5
  18. spring.datasource.maxActive=20
  19. # 配置获取连接等待超时的时间
  20. spring.datasource.maxWait=60000
  21. # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
  22. spring.datasource.timeBetweenEvictionRunsMillis=60000
  23. # 配置一个连接在池中最小生存的时间,单位是毫秒
  24. spring.datasource.minEvictableIdleTimeMillis=300000
  25. spring.datasource.validationQuery=SELECT 1 FROM DUAL
  26. spring.datasource.testWhileIdle=true
  27. spring.datasource.testOnBorrow=false
  28. spring.datasource.testOnReturn=false
  29. # 打开PSCache,并且指定每个连接上PSCache的大小
  30. spring.datasource.poolPreparedStatements=true
  31. spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
  32. # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
  33. spring.datasource.filters=stat,wall,log4j
  34. # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
  35. spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
  36. ## 打印SQL语句
  37. logging.level.com.duoduo.mybatis.mapper=debug

四、配置数据源类

user数据库连接配置类

  1. @Configuration
  2. @MapperScan(basePackages = UserDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "userSqlSessionFactory")
  3. public class UserDataSourceConfig {
  4. static final String PACKAGE = "com.duoduo.mybatis.mapper.user";
  5. static final String MAPPER_LOCATION = "classpath:mapper/user/*.xml";
  6. @Value("${datasource.user.url}")
  7. private String url;
  8. @Value("${datasource.user.username}")
  9. private String username;
  10. @Value("${datasource.user.password}")
  11. private String password;
  12. @Value("${datasource.user.driverClassName}")
  13. private String driverClassName;
  14. @Value("${spring.datasource.initialSize}")
  15. private int initialSize;
  16. @Value("${spring.datasource.minIdle}")
  17. private int minIdle;
  18. @Value("${spring.datasource.maxActive}")
  19. private int maxActive;
  20. @Value("${spring.datasource.maxWait}")
  21. private int maxWait;
  22. @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
  23. private int timeBetweenEvictionRunsMillis;
  24. @Value("${spring.datasource.minEvictableIdleTimeMillis}")
  25. private int minEvictableIdleTimeMillis;
  26. @Value("${spring.datasource.validationQuery}")
  27. private String validationQuery;
  28. @Value("${spring.datasource.testWhileIdle}")
  29. private boolean testWhileIdle;
  30. @Value("${spring.datasource.testOnBorrow}")
  31. private boolean testOnBorrow;
  32. @Value("${spring.datasource.testOnReturn}")
  33. private boolean testOnReturn;
  34. @Value("${spring.datasource.poolPreparedStatements}")
  35. private boolean poolPreparedStatements;
  36. @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
  37. private int maxPoolPreparedStatementPerConnectionSize;
  38. @Value("${spring.datasource.filters}")
  39. private String filters;
  40. @Value("{spring.datasource.connectionProperties}")
  41. private String connectionProperties;
  42. @Bean(name = "userDatasource")
  43. public DataSource userDatasource() {
  44. DruidDataSource dataSource = new DruidDataSource();
  45. dataSource.setUrl(url);
  46. dataSource.setUsername(username);
  47. dataSource.setPassword(password);
  48. dataSource.setDriverClassName(driverClassName);
  49. //具体配置
  50. dataSource.setInitialSize(initialSize);
  51. dataSource.setMinIdle(minIdle);
  52. dataSource.setMaxActive(maxActive);
  53. dataSource.setMaxWait(maxWait);
  54. dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
  55. dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
  56. dataSource.setValidationQuery(validationQuery);
  57. dataSource.setTestWhileIdle(testWhileIdle);
  58. dataSource.setTestOnBorrow(testOnBorrow);
  59. dataSource.setTestOnReturn(testOnReturn);
  60. dataSource.setPoolPreparedStatements(poolPreparedStatements);
  61. dataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
  62. try {
  63. dataSource.setFilters(filters);
  64. } catch (SQLException e) {
  65. e.printStackTrace();
  66. }
  67. dataSource.setConnectionProperties(connectionProperties);
  68. return dataSource;
  69. }
  70. @Bean(name = "userTransactionManager")
  71. public DataSourceTransactionManager userTransactionManager() {
  72. return new DataSourceTransactionManager(userDatasource());
  73. }
  74. @Bean(name = "userSqlSessionFactory")
  75. public SqlSessionFactory userSqlSessionFactory(@Qualifier("userDatasource") DataSource userDatasource)
  76. throws Exception {
  77. final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
  78. sessionFactory.setDataSource(userDatasource);
  79. sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
  80. .getResources(UserDataSourceConfig.MAPPER_LOCATION));
  81. return sessionFactory.getObject();
  82. }
  83. }

order数据库连接配置类

  1. @Configuration
  2. @MapperScan(basePackages = OrderDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "orderSqlSessionFactory")
  3. public class OrderDataSourceConfig {
  4. static final String PACKAGE = "com.duoduo.mybatis.mapper.order";
  5. static final String MAPPER_LOCATION = "classpath:mapper/order/*.xml";
  6. @Value("${datasource.order.url}")
  7. private String url;
  8. @Value("${datasource.order.username}")
  9. private String username;
  10. @Value("${datasource.order.password}")
  11. private String password;
  12. @Value("${datasource.order.driverClassName}")
  13. private String driverClass;
  14. @Value("${spring.datasource.initialSize}")
  15. private int initialSize;
  16. @Value("${spring.datasource.minIdle}")
  17. private int minIdle;
  18. @Value("${spring.datasource.maxActive}")
  19. private int maxActive;
  20. @Value("${spring.datasource.maxWait}")
  21. private int maxWait;
  22. @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
  23. private int timeBetweenEvictionRunsMillis;
  24. @Value("${spring.datasource.minEvictableIdleTimeMillis}")
  25. private int minEvictableIdleTimeMillis;
  26. @Value("${spring.datasource.validationQuery}")
  27. private String validationQuery;
  28. @Value("${spring.datasource.testWhileIdle}")
  29. private boolean testWhileIdle;
  30. @Value("${spring.datasource.testOnBorrow}")
  31. private boolean testOnBorrow;
  32. @Value("${spring.datasource.testOnReturn}")
  33. private boolean testOnReturn;
  34. @Value("${spring.datasource.poolPreparedStatements}")
  35. private boolean poolPreparedStatements;
  36. @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
  37. private int maxPoolPreparedStatementPerConnectionSize;
  38. @Value("${spring.datasource.filters}")
  39. private String filters;
  40. @Value("{spring.datasource.connectionProperties}")
  41. private String connectionProperties;
  42. @Bean(name = "orderDataSource")
  43. public DataSource orderDataSource() {
  44. DruidDataSource dataSource = new DruidDataSource();
  45. dataSource.setUrl(url);
  46. dataSource.setUsername(username);
  47. dataSource.setPassword(password);
  48. dataSource.setDriverClassName(driverClass);
  49. //具体配置
  50. dataSource.setInitialSize(initialSize);
  51. dataSource.setMinIdle(minIdle);
  52. dataSource.setMaxActive(maxActive);
  53. dataSource.setMaxWait(maxWait);
  54. dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
  55. dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
  56. dataSource.setValidationQuery(validationQuery);
  57. dataSource.setTestWhileIdle(testWhileIdle);
  58. dataSource.setTestOnBorrow(testOnBorrow);
  59. dataSource.setTestOnReturn(testOnReturn);
  60. dataSource.setPoolPreparedStatements(poolPreparedStatements);
  61. dataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
  62. try {
  63. dataSource.setFilters(filters);
  64. } catch (SQLException e) {
  65. e.printStackTrace();
  66. }
  67. dataSource.setConnectionProperties(connectionProperties);
  68. return dataSource;
  69. }
  70. @Bean(name = "orderTransactionManager")
  71. public DataSourceTransactionManager orderTransactionManager() {
  72. return new DataSourceTransactionManager(orderDataSource());
  73. }
  74. @Bean(name = "orderSqlSessionFactory")
  75. public SqlSessionFactory orderSqlSessionFactory(@Qualifier("orderDataSource") DataSource orderDataSource)
  76. throws Exception {
  77. final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
  78. sessionFactory.setDataSource(orderDataSource);
  79. sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
  80. .getResources(OrderDataSourceConfig.MAPPER_LOCATION));
  81. sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(OrderDataSourceConfig.MAPPER_LOCATION));
  82. return sessionFactory.getObject();
  83. }
  84. }

五、书写mapper  and  xml

 com.duoduo.mybatis.mapper.user.UserMapper.java

  1. package com.duoduo.mybatis.mapper.user;
  2. import com.duoduo.mybatis.entity.User;
  3. import org.springframework.stereotype.Repository;
  4. /***
  5. * @date: 2022/7/1
  6. * @author: 微信公众号:深入技术架构
  7. * @description: TODO
  8. */
  9. @Repository
  10. public interface UserMapper {
  11. User findUser(int id);
  12. }

 com.duoduo.mybatis.mapper.order.OrderMapper.java

  1. package com.duoduo.mybatis.mapper.order;
  2. import com.duoduo.mybatis.entity.Order;
  3. import org.springframework.stereotype.Repository;
  4. /***
  5. * @date: 2022/7/1
  6. * @author: 微信公众号:深入技术架构
  7. * @description: TODO
  8. */
  9. @Repository
  10. public interface OrderMapper {
  11. Order findOrder(int id);
  12. }

resource/mapper/user/UserMapper.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.duoduo.mybatis.mapper.user.UserMapper">
  4. <resultMap id="BaseResultMap" type="com.duoduo.mybatis.entity.User">
  5. <result column="id" jdbcType="INTEGER" property="id" />
  6. <result column="userName" jdbcType="VARCHAR" property="userName" />
  7. <result column="passWord" jdbcType="VARCHAR" property="passWord" />
  8. <result column="realName" jdbcType="VARCHAR" property="realName" />
  9. </resultMap>
  10. <select id="findUser" resultType="com.duoduo.mybatis.entity.User">
  11. select * from user where id = #{id}
  12. </select>
  13. </mapper>

resource/mapper/order/OrderMapper.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.duoduo.mybatis.mapper.order.OrderMapper">
  4. <resultMap id="BaseResultMap" type="com.duoduo.mybatis.entity.Order">
  5. <result column="orderId" jdbcType="INTEGER" property="orderId" />
  6. <result column="orderName" jdbcType="VARCHAR" property="orderName" />
  7. </resultMap>
  8. <select id="findOrder" resultType="com.duoduo.mybatis.entity.Order">
  9. select * from `order` where orderId = #{id}
  10. </select>
  11. </mapper>

六、书写service

com.duoduo.mybatis.service.UserService.java
  1. package com.duoduo.mybatis.service;
  2. import com.duoduo.mybatis.entity.User;
  3. import com.duoduo.mybatis.mapper.user.UserMapper;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Service;
  6. /***
  7. * @date: 2022/7/1
  8. * @author: fenghaikuan
  9. * @description: TODO
  10. */
  11. @Service
  12. public class UserService {
  13. @Autowired
  14. UserMapper userMapper;
  15. public User findUser(int id){
  16. return userMapper.findUser(id);
  17. }
  18. }
com.duoduo.mybatis.service.OrderService.java
  1. package com.duoduo.mybatis.service;
  2. import com.duoduo.mybatis.entity.Order;
  3. import com.duoduo.mybatis.mapper.order.OrderMapper;
  4. import org.apache.ibatis.annotations.Mapper;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Service;
  7. /***
  8. * @date: 2022/7/1
  9. * @author: fenghaikuan
  10. * @description: TODO
  11. */
  12. @Service
  13. public class OrderService {
  14. @Autowired
  15. OrderMapper orderMapper;
  16. public Order findOrder(int id){
  17. return orderMapper.findOrder(id);
  18. }
  19. }

七、书写controller

com.duoduo.mybatis.controller.UserController.java
  1. package com.duoduo.mybatis.controller;
  2. import com.duoduo.mybatis.service.UserService;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.web.bind.annotation.PathVariable;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import org.springframework.web.bind.annotation.RestController;
  7. /***
  8. * @date: 2022/7/1
  9. * @author: fenghaikuan
  10. * @description: TODO
  11. */
  12. @RestController
  13. public class UserController {
  14. @Autowired
  15. private UserService userService;
  16. @RequestMapping("/getUser/{id}")
  17. public String getUser(@PathVariable int id){
  18. return userService.findUser(id).toString();
  19. }
  20. }

com.duoduo.mybatis.controller.OrderController.java

  1. package com.duoduo.mybatis.controller;
  2. import com.duoduo.mybatis.service.OrderService;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.web.bind.annotation.PathVariable;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import org.springframework.web.bind.annotation.RestController;
  7. /***
  8. * @date: 2022/7/1
  9. * @author: fenghaikuan
  10. * @description: TODO
  11. */
  12. @RestController
  13. public class OrderController {
  14. @Autowired
  15. private OrderService orderService;
  16. @RequestMapping("getOrder/{id}")
  17. public String getOrder(@PathVariable int id){
  18. return orderService.findOrder(id).toString();
  19. }
  20. }

八、Mysql 数据库文件

  1. user数据库执行:
  2. CREATE TABLE `user` (
  3. `id` int NOT NULL AUTO_INCREMENT,
  4. `userName` varchar(32) NOT NULL,
  5. `passWord` varchar(50) NOT NULL,
  6. `realName` varchar(32) DEFAULT NULL,
  7. PRIMARY KEY (`id`)
  8. ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb3;
  9. INSERT INTO `user` VALUES (1, '张三', 'password', '小张');
  10. order数据库执行:
  11. CREATE TABLE `order` (
  12. `orderId` int NOT NULL AUTO_INCREMENT,
  13. `orderName` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  14. PRIMARY KEY (`orderId`) USING BTREE
  15. ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb3;
  16. INSERT INTO `order` VALUES (1, '订单名称');

九、测试

http://localhost:8080/getUser/1

http://localhost:8080/getOrder/1

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

闽ICP备14008679号