找回密码
 立即注册
首页 业界区 业界 Springboot 项目配置多数据源

Springboot 项目配置多数据源

左丘雅秀 昨天 11:19
基础环境

java8、springboot2.2.13、mybatis、mysql5.x、oracle
项目配置

1.application.yml
  1. spring:
  2.   datasource:
  3.     mysql1:
  4.       username: abc
  5.       password: 123456
  6.       url: jdbc:mysql://127.0.0.1:3306/panda?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=GMT%2B8&useSSL=false
  7.       driver-class-name: com.mysql.cj.jdbc.Driver
  8.       # 使用druid数据源
  9.       type: com.alibaba.druid.pool.DruidDataSource
  10.     oracle1:
  11.       url: jdbc:oracle:thin:@127.0.0.1:1521:oracle
  12.       username: default
  13.       password: 123456
  14.       driver-class-name: oracle.jdbc.driver.OracleDriver
  15.       # 使用druid数据源
  16.       type: com.alibaba.druid.pool.DruidDataSource
复制代码
2.数据源配置
有三个注意点,其一是 @Primary 作用是标记哪个是主数据源(默认不指定数据源时会调用的数据源);其二是 basePackages 配置的是实际mapper路径,不同数据源路径不能混淆;其三是 setMapperLocations 配置的路径要加上 “classpath:” 前缀,才能找到对应包下的 .xml 文件。
  1. import org.springframework.boot.context.properties.ConfigurationProperties;
  2. import org.springframework.boot.jdbc.DataSourceBuilder;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.context.annotation.Primary;
  6. import javax.sql.DataSource;
  7. @Configuration
  8. public class AllDataSourceConfig {
  9.     @Bean(name = "safeDrivingDataSource")
  10.     @ConfigurationProperties(prefix = "spring.datasource.mysql1") // application.yml 中对应属性的前缀
  11.     @Primary
  12.     public DataSource safeDrivingDataSource() {
  13.         return DataSourceBuilder.create().type(com.alibaba.druid.pool.DruidDataSource.class).build();
  14.     }
  15.     @Bean(name = "emmpAppDataSource")
  16.     @ConfigurationProperties(prefix = "spring.datasource.oracle1")
  17.     public DataSource emmpappDataSource() {
  18.         return DataSourceBuilder.create().type(com.alibaba.druid.pool.DruidDataSource.class).build();
  19.     }
  20. }
  21. import org.apache.ibatis.session.SqlSessionFactory;
  22. import org.mybatis.spring.SqlSessionFactoryBean;
  23. import org.mybatis.spring.SqlSessionTemplate;
  24. import org.mybatis.spring.annotation.MapperScan;
  25. import org.springframework.beans.factory.annotation.Qualifier;
  26. import org.springframework.context.annotation.Bean;
  27. import org.springframework.context.annotation.Configuration;
  28. import org.springframework.context.annotation.Primary;
  29. import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
  30. import org.springframework.jdbc.datasource.DataSourceTransactionManager;
  31. import javax.sql.DataSource;
  32. @Configuration
  33. @MapperScan(basePackages = "com.emmp.safedriving.dao.mapper.ds1", sqlSessionFactoryRef = "safeDrivingSqlSessionFactory")
  34. public class SafeDrivingDataSourceConfig {
  35.     @Bean("safeDrivingSqlSessionFactory")
  36.     @Primary
  37.     public SqlSessionFactory sqlSessionFactory(@Qualifier("safeDrivingDataSource") DataSource dataSource) throws Exception {
  38.         SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
  39.         org.apache.ibatis.session.Configuration mybatisConfig = new org.apache.ibatis.session.Configuration();
  40.         mybatisConfig.setLazyLoadingEnabled(true);
  41.         mybatisConfig.setAggressiveLazyLoading(false);
  42.         mybatisConfig.setMapUnderscoreToCamelCase(true);
  43.         sqlSessionFactoryBean.setConfiguration(mybatisConfig);
  44.         sqlSessionFactoryBean.setDataSource(dataSource);
  45.         sqlSessionFactoryBean.setMapperLocations(
  46.                 new PathMatchingResourcePatternResolver().getResources("classpath:com/emmp/safedriving/dao/mapper/ds1/xml/*.xml"));
  47.         return sqlSessionFactoryBean.getObject();
  48.     }
  49.     @Bean("safeDrivingDataSourceTransactionManager")
  50.     @Primary
  51.     public DataSourceTransactionManager dataSourceTransactionManager(@Qualifier("safeDrivingDataSource") DataSource dataSource){
  52.         return new DataSourceTransactionManager(dataSource);
  53.     }
  54.     @Bean(name = "safeDrivingSqlSessionTemplate")
  55.     @Primary
  56.     public SqlSessionTemplate sqlSessionTemplate(@Qualifier("safeDrivingSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
  57.         return new SqlSessionTemplate(sqlSessionFactory);
  58.     }
  59. }
  60. import org.apache.ibatis.session.SqlSessionFactory;
  61. import org.mybatis.spring.SqlSessionFactoryBean;
  62. import org.mybatis.spring.SqlSessionTemplate;
  63. import org.mybatis.spring.annotation.MapperScan;
  64. import org.springframework.beans.factory.annotation.Qualifier;
  65. import org.springframework.context.annotation.Bean;
  66. import org.springframework.context.annotation.Configuration;
  67. import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
  68. import org.springframework.jdbc.datasource.DataSourceTransactionManager;
  69. import javax.sql.DataSource;
  70. @Configuration
  71. @MapperScan(basePackages = "com.emmp.safedriving.dao.mapper.ds2", sqlSessionFactoryRef = "emmpAppSqlSessionFactory")
  72. public class EmmpAppDataSourceConfig {
  73.     @Bean("emmpAppSqlSessionFactory")
  74.     public SqlSessionFactory sqlSessionFactory(@Qualifier("emmpAppDataSource") DataSource dataSource) throws Exception {
  75.         SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
  76.         org.apache.ibatis.session.Configuration mybatisConfig = new org.apache.ibatis.session.Configuration();
  77.         mybatisConfig.setLazyLoadingEnabled(true);
  78.         mybatisConfig.setAggressiveLazyLoading(false);
  79.         mybatisConfig.setMapUnderscoreToCamelCase(true);
  80.         sqlSessionFactoryBean.setConfiguration(mybatisConfig);
  81.         sqlSessionFactoryBean.setDataSource(dataSource);
  82.         sqlSessionFactoryBean.setMapperLocations(
  83.                 new PathMatchingResourcePatternResolver().getResources("classpath:com/emmp/safedriving/dao/mapper/ds2/xml/*.xml"));
  84.         return sqlSessionFactoryBean.getObject();
  85.     }
  86.     @Bean("emmpAppDataSourceTransactionManager")
  87.     public DataSourceTransactionManager dataSourceTransactionManager(@Qualifier("emmpAppDataSource") DataSource dataSource){
  88.         return new DataSourceTransactionManager(dataSource);
  89.     }
  90.     @Bean(name = "emmpAppSqlSessionTemplate")
  91.     public SqlSessionTemplate sqlSessionTemplate(@Qualifier("emmpAppSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
  92.         return new SqlSessionTemplate(sqlSessionFactory);
  93.     }
  94. }
复制代码
3.启动类配置
不需要再添加 @MapperScan
  1. @SpringBootApplication(
  2.         exclude = {
  3.                 DataSourceAutoConfiguration.class,  // 排除默认数据源配置
  4.                 DataSourceTransactionManagerAutoConfiguration.class,  // 排除默认事务管理器
  5.                 MybatisAutoConfiguration.class  // 排除 MyBatis 默认配置
  6.         }
  7. )
复制代码
4.mapper 定义示例
  1. // 映射对象定义
  2. import lombok.AllArgsConstructor;
  3. import lombok.Builder;
  4. import lombok.Data;
  5. import lombok.NoArgsConstructor;
  6. import lombok.experimental.Accessors;
  7. import java.time.LocalDate;
  8. import java.time.LocalDateTime;
  9. @Data
  10. @Builder
  11. @Accessors(chain = true)
  12. @NoArgsConstructor
  13. @AllArgsConstructor
  14. public class DriverInfo {
  15.     private Long id;
  16.     private String driverName;
  17.    
  18. }
  19. import org.apache.ibatis.annotations.Mapper;
  20. import java.util.List;
  21. @Mapper
  22. public interface DriverInfoMapper {
  23.     List<DriverInfo> queryAll();
  24.     List<DriverInfo> queryByCellphone(String cellphone);
  25. }
复制代码
对应 DriverInfoMapper.xml 配置
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3.         "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <mapper namespace="com.emmp.safedriving.dao.mapper.ds2.DriverInfoMapper">
  5.     <resultMap id="entity" type="com.emmp.safedriving.dao.entity.DriverInfo">
  6.         <result property="id" column="ID"/>
  7.         <result property="driverName" column="DRIVERNAME"/>
  8.     </resultMap>
  9.     <select id="queryAll" resultMap="entity">
  10.         SELECT * FROM DRIVER_INFO
  11.     </select>
  12.     <select id="queryByCellphone" resultMap="entity">
  13.         SELECT * FROM DRIVER_INFO
  14.         WHERE CELLPHONE = #{cellphone}
  15.         ORDER BY ID DESC
  16.     </select>
  17. </mapper>
复制代码
来源:豆瓜网用户自行投稿发布,如果侵权,请联系站长删除

相关推荐

您需要登录后才可以回帖 登录 | 立即注册