有时候项目中会遇到需要配置双数据源的情况,到SpringBoot2.0版本后和之前配置双数据源的方法有些区别,这里我用的SpringBoot版本是2.0.3,废话不多说,给出主要步骤:

一、项目依赖pom.xml配置

<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.0.3.RELEASE</version><relativePath/>
</parent>
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>com.microsoft.sqlserver</groupId><artifactId>mssql-jdbc</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency>

二、application.properties配置文件配置

datasource.main.jdbc-url=jdbc:sqlserver://xxxxxxxxxx:1433;DatabaseName=xxx
datasource.main.username=sa
datasource.main.password=xxxxxxx
datasource.main.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.jpa.main.database=sql_server
spring.jpa.hibernate.main-dialect=org.hibernate.dialect.SQLServer2008Dialect
datasource.main.configuration.maximum-pool-size=30datasource.second.jdbc-url=jdbc:mysql://localhost:3306/xxxxx?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true
datasource.second.username=root
datasource.second.password=root
datasource.second.driver-class-name=com.mysql.jdbc.Driver
datasource.second.database=mysql
datasource.second.configuration.maximum-pool-size=30
mybatis.configuration.mapUnderscoreToCamelCase=true
spring.jpa.hibernate.second-dialect=org.hibernate.dialect.MySQL5Dialect

三、配置双数据源主要代码

1.创建主从数据源DataSourceConfig配置类

@Configuration
public class DataSourceConfig {@Bean(name = "primaryDataSource")
@Primary
@Qualifier("primaryDataSource")
@ConfigurationProperties(prefix = "datasource.main")
public DataSource primaryDatasource() {return DataSourceBuilder.create().build();
}@Bean(name = "secondaryDataSource")
@Qualifier("secondaryDataSource")
@ConfigurationProperties(prefix = "datasource.second")
public DataSource secondaryDataSource() {return DataSourceBuilder.create().build();
}}

2.主数据源的配置

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactoryPrimary",//配置连接工厂 entityManagerFactorytransactionManagerRef = "transactionManagerPrimary", //配置 事物管理器  transactionManagerbasePackages = {"com.greek.www.dao"}//设置持久层所在位置
)
public class PrimaryConfig {@Autowired
private JpaProperties jpaProperties;@Autowired
@Qualifier("primaryDataSource")
private DataSource primaryDataSource;// 自动注入配置好的数据源@Value("${spring.jpa.hibernate.main-dialect}")
private String primaryDialect;// 获取对应的数据库方言/**** @param builder* @return*/
@Bean(name = "entityManagerFactoryPrimary")
@Primary
public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(EntityManagerFactoryBuilder builder) {return builder//设置数据源.dataSource(primaryDataSource)//设置数据源属性.properties(getVendorProperties(primaryDataSource))//设置实体类所在位置.扫描所有带有 @Entity 注解的类.packages("com.greek.www.entity")// Spring会将EntityManagerFactory注入到Repository之中.有了 EntityManagerFactory之后,// Repository就能用它来创建 EntityManager 了,然后 EntityManager 就可以针对数据库执行操作.persistenceUnit("primaryPersistenceUnit").build();}private Map<String, String> getVendorProperties(DataSource dataSource) {Map<String,String> map = new HashMap<>();map.put("hibernate.dialect",primaryDialect);// 设置对应的数据库方言//jpaProperties.getHibernate().getNaming().setPhysicalStrategy("org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl");jpaProperties.setProperties(map);return jpaProperties.getProperties();
}/*** 配置事物管理器** @param builder* @return*/
@Bean(name = "transactionManagerPrimary")
@Primary
PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
}
}

3.从数据源的配置

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef="entityManagerFactorySecondary",transactionManagerRef="transactionManagerSecondary",basePackages= { "com.greek.www.repository" })
public class SecondaryConfig {@Autowired
private JpaProperties jpaProperties;@Autowired
@Qualifier("secondaryDataSource")
private DataSource secondaryDataSource;@Value("${spring.jpa.hibernate.second-dialect}")
private String secondaryDialect;@Bean(name = "entityManagerSecondary")
public EntityManager entityManager(EntityManagerFactoryBuilder builder) {return entityManagerFactorySecondary(builder).getObject().createEntityManager();
}@Bean(name = "entityManagerFactorySecondary")
public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary (EntityManagerFactoryBuilder builder) {return builder.dataSource(secondaryDataSource).properties(getVendorProperties(secondaryDataSource)).packages("com.greek.www.domain").persistenceUnit("secondaryPersistenceUnit").build();
}private Map<String, String> getVendorProperties(DataSource dataSource) {Map<String,String> map = new HashMap<>();map.put("hibernate.dialect",secondaryDialect);// jpaProperties.getHibernate().getNaming().setPhysicalStrategy("org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy");//jpaProperties.getHibernate().getNaming().setImplicitStrategy("org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy");jpaProperties.setProperties(map);return jpaProperties.getProperties();
}@Bean(name = "transactionManagerSecondary")
PlatformTransactionManager transactionManagerSecondary(EntityManagerFactoryBuilder builder) {return new JpaTransactionManager(entityManagerFactorySecondary(builder).getObject());
}}

这样双数据源的配置就完成了,但是有一个问题我没有解决,就是mysql数据库有下划线的字段不能解析,必须在实体类中加上注解指定字段,比如:

@Column(name = "rpt_time")
private Date rptTime;

双数据源的字段命名策略设置不生效,不知道为什么,如果有答案的小伙伴希望能告知。不胜感激!

访问我的达人课

访问我的博客 Wang's Blog

关注我的微信公众号获取更多资源

SpringBoot+SpringDataJpa配置双数据源SqlServer和Mysql相关推荐

  1. mybatis多数据源配置_随笔:springboot+mybatis 配置双数据源

    山石彦 | 作者 urlify.cn/vQzIne | 来源 最近工作中有用到双数据源,一个项目(中台)中需要操作两个不同的数据库.当时考虑到了两种方式, 1.通过http请求访问(A项目访问d1数据 ...

  2. springboot + JPA 配置双数据源

    一.首先配置application.yml文件设置主从数据库 spring:servlet:multipart:max-file-size: 20MBmax-request-size: 20MBpro ...

  3. springboot+jpa配置多数据源(Oracle+SqlServer)

    本贴主要讲解配置多数据源 springboot+jpa的整合需要自行准备好 1.maven中要导入Oracle和SqlServer的jar包 <dependency><groupId ...

  4. SpringMVC+Mybatis+Maven搭建 简单配置双数据源

    POM.xml引包常用的 mybatis  以及 mybatis-spting  spring-webmvc log4j spring-jdbc servler-api spring-jdbc < ...

  5. SSM项目_配置双数据源

    近日项目中因为涉及到一个需求是A系统某表的数据要与B系统的某表数据在数据上出现不一致的情况,需要做一个数据比对功能,这时候就涉及到两个系统的数据库的数据比对. 方案一,将A系统的数据导出到Excel文 ...

  6. springboot jpa 配置多数据源

    jpa 多数据源配置 多个 mysql 数据库配置 springboot jpa 配置多数据源其实也并不难,只需要在 properties 或者 yml中简单配置并在项目中引入配置即可. 下面以 ym ...

  7. SpringBoot JPA配置多数据源(同类型库)教程

    SpringBoot项目配置多数据源主要分为以下个步骤: 确定好所连接的数据库的资源(包括url username password) 将两个库的信息写入到配置文件中(application.yaml ...

  8. springdatajpa配置多数据源

    springboot项目配置多数据源 springboot从2.0开始默认数据库连接池 Hikari,在配置多数据源时想自定义连接池配置可以参考如下- pom.xml <parent>&l ...

  9. SpringBoot配置多数据源Mybatis/MybatisPlus/mysql

    一.前言 项目开发过程中,单一数据源不能满足开发需求或者需要用到主从数据库的时候,引入多数据源配置在项目中显得尤为必要.下面简单介绍一种在spingboot中结合mybatis针对同类型的数据源mys ...

最新文章

  1. excel去掉一行文字中的逗号合并在一起_Python使用pandas库五行代码合并excel
  2. libgdx游戏引擎开发笔记(一)引擎介绍和Helloworld
  3. java快捷键 --_Java中的快捷方式“或分配”(| =)运算符
  4. php与eCharts结合,23.安装php和echarts进行结合展示图表
  5. JMeter——并发测试工具类安装及使用
  6. 有序数组中插入元素依然保持有序
  7. shell基础命令管理
  8. js进阶 11-8 jquery如何获取元素相对于父元素的位置
  9. 随机取出若干条记录的SQL语句
  10. spring源码:BeanFactoryPostProcessor和BeanDefinitionRegistryPostProcessor的区别
  11. PyCharm破解版 mac
  12. 猿大师VLC播放程序播放RTSP实时视频提示“系统找不到指定文件”
  13. python 批处理合并表格_高效办公4——Python批量合并Excel指定列相同内容单元格...
  14. 萝卜青菜各有所爱------TypeScript VS JavaScript
  15. 最新机器人视觉系统介绍,给机器人装上“眼睛”
  16. vxworks下的脚本script创建和使用(相当于windows下的autoexec.bat)
  17. 电子设计硬件可靠性设计----总结2
  18. PostgreSQL高可用中间件—Pgpool-Ⅱ
  19. MATLAB atan 和 atan2
  20. 防火墙(360天堤)双因素身份认证解决方案

热门文章

  1. Python基础07互评成绩
  2. python必备软件百度网盘_【亲测好用!】python实现批量百度云批量转存工具
  3. 【MacBook M1】 安装动手学深度学习d2l包+jupyter notebook运行
  4. 关于Ubuntu没有声音的解决方法
  5. Python3:使用函数计算-输入日期,计算该日期是当年中第多少天
  6. 微信扫码自动跳转技术
  7. 大搜车:“薄利多销”是否适合二手车市场?
  8. MyBatis中#{}和${}的作用与区别
  9. Laravel事件广播项目中使用laravel-echo-server
  10. 1964503-39-6,Carboxy-PEG4-phosphonic acid ethyl ester包含羧酸端基和膦酸乙酯部分