绑定完请刷新页面
取消
刷新

分享好友

×
取消 复制
SpringBoot+SpringDataJpa配置双数据源SqlServer和Mysql
2023-02-23 17:21:08

有时候项目中会遇到需要配置双数据源的情况,到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=30
datasource.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",//配置连接工厂 entityManagerFactory
transactionManagerRef = "transactionManagerPrimary", 配置 事物管理器  transactionManager
basePackages = {"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;



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



本文来源https://www.modb.pro/db/158981

分享好友

分享这个小栈给你的朋友们,一起进步吧。

Microsoft SQL Server
创建时间:2022-03-30 11:29:11
Microsoft SQL Server
展开
订阅须知

• 所有用户可根据关注领域订阅专区或所有专区

• 付费订阅:虚拟交易,一经交易不退款;若特殊情况,可3日内客服咨询

• 专区发布评论属默认订阅所评论专区(除付费小栈外)

技术专家

查看更多
  • itt0918
    专家
戳我,来吐槽~