SpringBoot+Jpa项目配置双数据源的实现

 更新时间:2021年12月23日 09:10:40   作者:爱唱歌的胖虎  
本文主要介绍了SpringBoot+Jpa项目配置双数据库源的实现,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

引言

今天为大家带来一些非常有用的实战技巧,比如在我们需要对两个数据库进行操作的时候而哦我们通常用的只是单数据库查询,这就触及到知识盲点了,那么废话不多说上代码!

配置yml文件

server:
  port: 8080
spring:
  profiles:
    active: dev
  jackson:
    time-zone: GMT+8  
    
# 这里是我们的数据库配置地方    
datasource:
    data1:  #这里是数据库一
      driverClassName: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://192.168.0.77:3306/test1?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&autoReconnect=true&failOverReadOnly=false&rewriteBatchedStatements=true
      username: root
      password: 123
      type: com.alibaba.druid.pool.DruidDataSource

    data2:  #这里是数据库二
      driverClassName: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://192.168.0.88:3306/test2?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&autoReconnect=true&failOverReadOnly=false&rewriteBatchedStatements=true
      username: root
      password: 123
      type: com.alibaba.druid.pool.DruidDataSource

当然到这里肯定是没有结束的,需要配置一些参数,否则启动会报错

创建数据源配置类

我们创建一个数据源的类,我们就给他取名为DataSourceConfig(这个名字自定义),在项目下创建一个包,方便管理

package com.eman.cdn.common.dataSource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

/**
 * @author https://blog.csdn.net/weixin_42782429?spm=1000.2115.3001.5343
 * @date 2021/12/21 11:35
 * <p>
 * description 数据源配置
 */
@Configuration
public class DataSourceConfig {

 # 这里是我们在yml文件配置的位置
    private final static String DB_TEST1 = "spring.datasource.test1";
    private final static String DB_TEST2= "spring.datasource.test1";


 # 这个Bean名字子自定义只要不是重复的Bean名字就行了
    @Bean(name = "test1Properties")
    @Qualifier("test1Properties")
    @Primary
    @ConfigurationProperties(DB_TEST1)
    public DataSourceProperties test1Properties() {
        return new DataSourceProperties();
    }

    @Bean(name = "test1DataSource")
    @Qualifier("test1DataSource")
    @Primary
    @ConfigurationProperties(prefix = DB_TEST1)
    public DataSource test1DataSource() {
        return test1Properties().initializeDataSourceBuilder().build();
    }


    @Bean(name = "test2Properties")
    @Qualifier("test2Properties")
    @ConfigurationProperties(DB_TEST2)
    public DataSourceProperties test2Properties() {
        return new DataSourceProperties();
    }

    @Bean(name = "test2DataSource")
    @Qualifier("test2DataSource")
    @ConfigurationProperties(prefix = DB_ANALYSIS)
    public DataSource test2DataSource() {
        return test2Properties().initializeDataSourceBuilder().build();
    }
}

为每个数据库创建配置类

由于需要用到Mybaitis-plus所以你得先导入Mybaitis-Plus的依赖

<!--mybatis-plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.0</version>
        </dependency>

package com.eman.xx.xxx.xx;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.Objects;

/**
 * @author tongJie
 * @date 2021/12/21 11:59
 * <p>
 * description  日志处理端数据库配置
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        // 配置连接工厂
        entityManagerFactoryRef = "tes1Factory",
        // 配置事物管理器
        transactionManagerRef = "tes1Transaction",
        // 设置Jpa 的 repository所在位置
        basePackages = {"com.xx.xx.xx.**.repository"}
)
// 设置扫描的mapper
@MapperScan(basePackages ="xx.xx.xx.test1.**.mapper", sqlSessionTemplateRef  = "tes1SqlSessionTemplate")
public class AnalysisDataBaseConfig {

    @Autowired
    @Qualifier("tes1DataSource")
    private DataSource analysisDataSource;

    @Autowired
    private JpaProperties jpaProperties;

    @Autowired
    private HibernateProperties properties;

    // 以下是jpa的配置

    /**
     * 连接工厂
     * @param builder 创建工具
     * @return 结果
     */
    @Bean(name = "tes1Factory")
    public LocalContainerEntityManagerFactoryBean tes1Factory(EntityManagerFactoryBuilder builder) {
        return builder
                // 设置数据源
                .dataSource(analysisDataSource)
                //设置实体类所在位置.扫描所有带有 @Entity 注解的类
                .packages("xx.xx.xx.tes1.**.entity")
                // Spring会将EntityManagerFactory注入到Repository之中.有了 EntityManagerFactory之后,
                // Repository就能用它来创建 EntityManager 了,然后 EntityManager 就可以针对数据库执行操作
                .persistenceUnit("tes1")
                // 为了加载yml中jpa下hibernate的相关配置
                .properties(properties.determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings()))
                .build();

    }

    /**
     * 配置事物管理器
     *
     * @param builder 创建工具
     * @return 结果
     */
    @Bean(name = "tes1Transaction")
    PlatformTransactionManager tes1Transaction(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(Objects.requireNonNull(analysisFactory(builder).getObject()));
    }

    // 以下是mybatis的配置

    /**
     * 配置sqlSessionFactory
     * @return 结果
     * @throws Exception 异常
     */
    @Bean("tes1SqlSessionFactory")
    public SqlSessionFactory tes1SqlSessionFactory() throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(analysisDataSource);
        sqlSessionFactory.setMapperLocations(new 
        //这里填写你mybaits的xml文件存放的路径
        PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/*.xml"));
        return sqlSessionFactory.getObject();
    }

    /**
     * 配置sqlSessionTemplate
     * @return 结果
     */
    @Bean(name = "tes1SqlSessionTemplate")
    public SqlSessionTemplate tes1SqlSessionTemplate() throws Exception {
        return new SqlSessionTemplate(tes1SqlSessionFactory());
    }
}

以此类推之后每增加一个数据库源就循环上面的方法
注意!!!!包一定要放对你配置的位置,否则不识别就会报错!!!!!!

到此这篇关于SpringBoot+Jpa项目配置双数据库源的实现的文章就介绍到这了,更多相关SpringBoot Jpa双数据库源内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • SpringBoot+Redis实现布隆过滤器的示例代码

    SpringBoot+Redis实现布隆过滤器的示例代码

    本文主要介绍了SpringBoot+Redis实现布隆过滤器的示例代码,文中根据实例编码详细介绍的十分详尽,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-03-03
  • Spring Bean初始化及销毁多种实现方式

    Spring Bean初始化及销毁多种实现方式

    这篇文章主要介绍了Spring Bean初始化及销毁多种实现方式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-11-11
  • Jenkins初级应用之Invoke Phing targets插件配置

    Jenkins初级应用之Invoke Phing targets插件配置

    这篇文章主要为大家介绍了Jenkins初级应用之Invoke Phing targets的插件配置,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步早日升职加薪<BR>
    2022-04-04
  • java中构造方法和普通方法的区别说明

    java中构造方法和普通方法的区别说明

    这篇文章主要介绍了java中构造方法和普通方法的区别说明,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-08-08
  • SpringBoot项目使用@Scheduled注解实现定时任务的方法

    SpringBoot项目使用@Scheduled注解实现定时任务的方法

    文章介绍了在SpringBoot项目中使用@Scheduled注解实现定时任务的三种方式:基于注解、基于接口和基于注解设定多线程定时任务,详细讲解了@Scheduled注解的使用方法、各个参数以及如何配置动态定时任务和多线程定时任务,感兴趣的朋友一起看看吧
    2025-03-03
  • Intellij IDEA下Spring Boot热切换配置

    Intellij IDEA下Spring Boot热切换配置

    这篇文章主要介绍了Intellij IDEA下Spring Boot热切换配置,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-08-08
  • 关于RestTemplate中的Get请求

    关于RestTemplate中的Get请求

    这篇文章主要介绍了关于RestTemplate中的Get请求,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-07-07
  • Git工具 conflict冲突问题解决方案

    Git工具 conflict冲突问题解决方案

    这篇文章主要介绍了Git工具 conflict冲突问题解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-09-09
  • SpringBoot创建maven多模块项目实战代码

    SpringBoot创建maven多模块项目实战代码

    本篇文章主要介绍了SpringBoot创建maven多模块项目实战代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-09-09
  • SpringBoot和Tomcat的关系解读

    SpringBoot和Tomcat的关系解读

    这篇文章主要介绍了SpringBoot和Tomcat的关系,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2025-03-03

最新评论