springboot Jpa多数据源(不同库)配置

springboot Jpa多数据源(不同库)配置一、前言springboot版本不同对多数据源配置代码有一定影响,部分方法和配置略有不同。本文采用的springboot版本为2.3.12,数据源为mysql和postgresql二、配置实战2.1基础pom<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</ar

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE稳定放心使用

一、前言

springboot版本不同对多数据源配置代码有一定影响,部分方法和配置略有不同。
本文采用的springboot版本为2.3.12,数据源为mysql和postgresql


二、配置实战

2.1 基础pom

<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter</artifactId>
	</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>
		<version>5.1.21</version>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-data-jpa</artifactId>
	</dependency>
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>${ 
   mysql.version}</version>
	</dependency>
</dependencies>

2.2 配置文件

spring.datasource.mysql.jdbc-url=jdbc:mysql://localhost:3306/heilongjiang?characterEncoding=UTF-8&useSSL=false&useTimezone=true&serverTimezone=GMT%2B8
spring.datasource.mysql.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.mysql.username=root
spring.datasource.mysql.password=123456

spring.datasource.pg.jdbc-url=jdbc:postgresql://localhost:5432/hljsyjt?useUnicode=true&characterEncoding=utf8&currentSchema=emergencydev,expert,public
spring.datasource.pg.driver-class-name=org.postgresql.Driver
spring.datasource.pg.username=postgres
spring.datasource.pg.password=postgres

spring.jpa.properties.hibernate.mysql-dialect=org.hibernate.dialect.MySQLDialect
spring.jpa.properties.hibernate.pg-dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults=false

2.3 数据源配置类

package com.gsafety.bg.industrial.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;


/** * @author Mr.wanter * @time 2021-8-11 0011 * @description */

@Configuration
public class DataSourceConfig { 
   

    @Bean("dataSourceMysql")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.mysql")
    public DataSource dataSourceMysql() { 
   
        return DataSourceBuilder.create().build();
    }


    @Bean("dataSourcePg")
    @ConfigurationProperties(prefix = "spring.datasource.pg")
    public DataSource dataSourcePg() { 
   
        return DataSourceBuilder.create().build();
    }
}

2.4 数据源指定配置类

mysql指定数据源:

package com.gsafety.bg.industrial.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
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.context.annotation.Primary;
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.HashMap;
import java.util.Map;

/** * @author Mr.wanter * @time 2021-8-11 0011 * @description */

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryMysql",//配置连接工厂 entityManagerFactory
        transactionManagerRef = "transactionManagerMysql", //配置 事物管理器 transactionManager
        basePackages = { 
   "com.gsafety.bg.industrial.dao"}//设置持久层所在位置
)
public class MysqlDataSourceConfig { 
   

    @Autowired
    private JpaProperties jpaProperties;

    @Autowired
    private HibernateProperties hibernateProperties;
    // 自动注入配置好的数据源
    @Autowired
    @Qualifier("dataSourceMysql")
    private DataSource mysqlDataSource;
    // 获取对应的数据库方言
    @Value("${spring.jpa.properties.hibernate.mysql-dialect}")
    private String mysqlDialect;

    /** * @param builder * @return */
    @Bean(name = "entityManagerFactoryMysql")
    @Primary
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryMysql(EntityManagerFactoryBuilder builder) { 
   
        Map<String, String> map = new HashMap<>();
        // 设置对应的数据库方言
        map.put("hibernate.dialect", mysqlDialect);
        jpaProperties.setProperties(map);
        Map<String, Object> properties = hibernateProperties.determineHibernateProperties(
                jpaProperties.getProperties(), new HibernateSettings());
        return builder
                //设置数据源
                .dataSource(mysqlDataSource)
                //设置数据源属性
                .properties(properties)
                //设置实体类所在位置.扫描所有带有 @Entity 注解的类
                .packages("com.gsafety.bg.industrial.dao.po")
                // Spring会将EntityManagerFactory注入到Repository之中.有了 EntityManagerFactory之后,
                // Repository就能用它来创建 EntityManager 了,然后 EntityManager 就可以针对数据库执行操作
                .persistenceUnit("mysqlPersistenceUnit")
                .build();
    }

    /** * 配置事物管理器 * * @param builder * @return */
    @Bean(name = "transactionManagerMysql")
    @Primary
    PlatformTransactionManager transactionManagerMysql(EntityManagerFactoryBuilder builder) { 
   
        return new JpaTransactionManager(entityManagerFactoryMysql(builder).getObject());
    }

}

pg指定数据源:

package com.gsafety.bg.industrial.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
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.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.HashMap;
import java.util.Map;

/** * @author Mr.wanter * @time 2021-8-11 0011 * @description */

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryPg",//配置连接工厂 entityManagerFactory
        transactionManagerRef = "transactionManagerPg", //配置 事物管理器 transactionManager
        basePackages = { 
   "com.gsafety.bg.data.dao"}//设置持久层所在位置
)
public class PgDataSourceConfig { 
   

    @Autowired
    private JpaProperties jpaProperties;

    @Autowired
    private HibernateProperties hibernateProperties;
    //自动注入配置好的数据源
    @Autowired
    @Qualifier("dataSourcePg")
    private DataSource PgDataSource;
    // 获取对应的数据库方言
    @Value("${spring.jpa.properties.hibernate.pg-dialect}")
    private String pgDialect;

    /** * @param builder * @return */
    @Bean(name = "entityManagerFactoryPg")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryPg(EntityManagerFactoryBuilder builder) { 
   
        Map<String, String> map = new HashMap<>();
        // 设置对应的数据库方言
        map.put("hibernate.dialect", pgDialect);
        jpaProperties.setProperties(map);
        Map<String, Object> properties = hibernateProperties.determineHibernateProperties(
                jpaProperties.getProperties(), new HibernateSettings());
        return builder
                //设置数据源
                .dataSource(PgDataSource)
                //设置数据源属性
                .properties(properties)
                //设置实体类所在位置.扫描所有带有 @Entity 注解的类
                .packages("com.gsafety.bg.data.dao.po")
                // Spring会将EntityManagerFactory注入到Repository之中.有了 EntityManagerFactory之后,
                // Repository就能用它来创建 EntityManager 了,然后 EntityManager 就可以针对数据库执行操作
                .persistenceUnit("pgPersistenceUnit")
                .build();

    }

    /** * 配置事物管理器 * * @param builder * @return */
    @Bean(name = "transactionManagerPg")
    PlatformTransactionManager transactionManagerPg(EntityManagerFactoryBuilder builder) { 
   
        return new JpaTransactionManager(entityManagerFactoryPg(builder).getObject());
    }

}

2.5 如何应用

数据源配置类中指定了扫描po和dao包的路径
例如entityManagerFactoryPg中的com.gsafety.bg.data.dao.po和com.gsafety.bg.data.dao
那么我们只需要在指定的包下创建po和dao即可,service包层次不受影响,自定义即可。
三数据源同理即可。
左侧为双数据源(与本篇实战内容一致),右侧为三数据源(三数据源目录结构示例)。
在这里插入图片描述

其他编码常规开发即可
po:

@Entity
@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "jc_repertory")
public class JcRepertoryPO implements Serializable { 
   

  //some fields

}

dao:

public interface JcRepertoryDao extends JpaRepository<JcRepertoryPO, String>, JpaSpecificationExecutor<JcRepertoryPO> { 
   

}

service:

public interface JcRepertoryService { 
   

    List<JcRepertoryPO> list();

}
@Service
public class JcRepertoryServiceImpl implements JcRepertoryService { 
   

    @Resource
    private JcRepertoryDao jcRepertoryDao;

    @Override
    public List<JcRepertoryPO> list() { 
   
        List<JcRepertoryPO> all = jcRepertoryDao.findAll();
        return all;
    }
}

controller 略
启动类添加扫描@SpringBootApplication_(_scanBasePackages = _{_"com.gsafety.bg.data", "com.gsafety.bg.industrial"_})_


三、遇到的问题

  1. 数据库连接报错 jdbcUrl is required with driverClassName

主要原因是在1.0 配置数据源的过程中主要是写成:spring.datasource.url 和spring.datasource.driverClassName。
而在2.0升级之后需要变更成:spring.datasource.jdbc-url和spring.datasource.driver-class-name

spring.datasource.pg.jdbc-url=jdbc:postgresql://localhost:5432/hljsyjt?useUnicode=true&characterEncoding=utf8&currentSchema=emergencydev,expert,public
spring.datasource.pg.driver-class-name=org.postgresql.Driver
  1. Paging query needs to have a Pageable parameter!

原系统中对jap的Repository进行了封装,采用常规方式调用即可。

  1. more than one ‘primary’ bean found among candidates

2.4 数据源指定配置类 中只有一个类中的方法添加 @Primary 另外一个不要加这个注解

  1. 互联网查询的代码中JpaProperties没有getHibernateProperties

与springboot版本有关,上面代码已修改。


在这里插入图片描述

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/179867.html原文链接:https://javaforall.net

(0)
上一篇 2022年10月20日 下午3:46
下一篇 2022年10月20日 下午3:46


相关推荐

  • 【网盘搭建】使用Rclone挂载Google Drive扩容服务器存储,实现网盘无限容量[通俗易懂]

    【网盘搭建】使用Rclone挂载Google Drive扩容服务器存储,实现网盘无限容量[通俗易懂]一,前言1,Rclone是什么Rclone是一个开源的命令行程序,用于管理云存储上的文件。它是云供应商Web存储界面的功能丰富的替代方案。超过50种云存储产品支持Rclone,包括S3对象存储,GoogleDrive,OneDrive等业务和消费者文件存储服务以及标准传输协议。2,它能用来干嘛可以备份(和加密)文件到云存储。从云存储还原(和解密)文件。将云数据镜像到其他云服务或本地。将数据迁移到云,或在云存储供应商之间迁移。将多个加密的,缓存的或多样化的云存储作为磁盘挂载。3,项目地址Gith

    2022年7月16日
    46
  • goland2021激活码【2021免费激活】

    (goland2021激活码)这是一篇idea技术相关文章,由全栈君为大家提供,主要知识点是关于2021JetBrains全家桶永久激活码的内容https://javaforall.net/100143.htmlIntelliJ2021最新激活注册码,破解教程可免费永久激活,亲测有效,上面是详细链接哦~9ADCNKZL59-eyJsaWNlb…

    2022年3月22日
    114
  • C语言丨线性表(二):线性链表(单链表)

    C语言丨线性表(二):线性链表(单链表)本文在介绍线性表的基本概念的基础上 重点介绍线性链表 单链表 及相应的算法

    2026年3月17日
    2
  • IDEA常用插件Top16

    IDEA常用插件Top16前言 精心推荐给大家的一些日常开发中最常用的效率插件 真心祝愿各位程序猿们开发效率提高 永不加班 一 AlibabaJavaC 代码规范检查工具 AlibabaJavaC 阿里开发的一款强大的代码规范检查工具 可以让自己写出易读性更高的代码 可以让团队代码风格尽量统一易于维护 前面博客已经介绍过了 不赘述了 Al

    2026年3月19日
    2
  • labview霍夫曼编码_香农编码与霍夫曼编码[通俗易懂]

    labview霍夫曼编码_香农编码与霍夫曼编码[通俗易懂]一.香农-范诺编码香农-范诺(Shannon-Fano)编码的目的是产生具有最小冗余的码词(codeword)。其基本思想是产生编码长度可变的码词。码词长度可变指的是,被编码的一些消息的符号可以用比较短的码词来表示。估计码词长度的准则是符号出现的概率。符号出现的概率越大,其码词的长度越短。香农-范诺编码算法需要用到下面两个基本概念:(1)熵(Entropy)某个事件的信息量(又称自信息)用Ii…

    2025年9月3日
    7
  • 程序包org.codehaus.jettison.json 不存在

    程序包org.codehaus.jettison.json 不存在描述 本地 maven 库有 jettison 包但是没有引到工程中项目不报错但是在打 jar 包的时候报错解决办法 查看 pom 文件有没有引用 jettison 我的是没有在 pom 文件加上 lt dependency gt lt groupId gt org codehaus jettison lt groupId gt lt artifactId gt

    2026年3月17日
    2

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号