龙空技术网

最细Springboot配置多数据源讲解

java星星。 129

前言:

现时同学们对“spring 配置多数据源”大概比较注意,兄弟们都需要了解一些“spring 配置多数据源”的相关文章。那么小编同时在网摘上收集了一些有关“spring 配置多数据源””的相关文章,希望大家能喜欢,各位老铁们一起来了解一下吧!

一、目录结构

目录结构

二、依赖包(pom.xml)

<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>mysql</groupId>        <artifactId>mysql-connector-java</artifactId>    </dependency>    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-configuration-processor</artifactId>        <optional>true</optional>    </dependency>    <dependency>        <groupId>org.projectlombok</groupId>        <artifactId>lombok</artifactId>        <version>1.18.2</version>    </dependency></dependencies>
三、配置文件
server:  port: 8080spring:  datasource:    first:      driver-class-name: com.mysql.jdbc.Driver      jdbc-url: jdbc:mysql://localhost:3306/first?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true      username: root      password: root    second:      driver-class-name: com.mysql.jdbc.Driver      jdbc-url: jdbc:mysql://localhost:3306/second?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true      username: root      password: root  jpa:    hibernate:      ddl-auto: update      naming:        physical-strategy: org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy        implicit-strategy: org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy    show-sql: true    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect    database: mysql
四、多数据源配置(jpa)

1. DataSourceConfiguration

package com.cetc.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;/** * 数据库配置 */@Configurationpublic class DataSourceConfiguration {    /**     *  第一个数据连接,默认优先级最高     * @return     */    @Bean(name = "dataSourceFirst")    @Primary    @ConfigurationProperties(prefix = "spring.datasource.first")    public DataSource dataSourceFirst() {        //这种方式的配置默认只满足spring的配置方式,如果使用其他数据连接(druid),需要自己独立获取配置        return DataSourceBuilder.create().build();    }    /**     * 第二个数据源     * @return     */    @Bean(name = "dataSourceSecond")    @ConfigurationProperties(prefix = "spring.datasource.second")    public DataSource dataSourceSecond() {        return DataSourceBuilder.create().build();    }}

说明:其实这里配置已经完成了,这里就配置了两个数据源了。可以加入对应的JdbcTemplate,这里不做介绍,比较简单

2. JpaFirstConfiguration

package com.cetc.config;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.boot.autoconfigure.domain.EntityScan;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.annotation.EnableTransactionManagement;import javax.persistence.EntityManager;import javax.sql.DataSource;/** * 第一个数据源,jpa的相关配置 */@Configuration@EntityScan(basePackages = "com.cetc.domain.first")//1、实体扫描//2、实体管理ref//3、事务管理@EnableJpaRepositories(        basePackages = "com.cetc.repository.first",        entityManagerFactoryRef = "firstEntityManagerFactoryBean",        transactionManagerRef = "firstTransactionManager")@EnableTransactionManagementpublic class JpaFirstConfiguration {    //第一个数据源,可以不加Qualifier    @Autowired    @Qualifier("dataSourceFirst")    private DataSource dataSource;    //jpa其他参数配置    @Autowired    private JpaProperties jpaProperties;    //实体管理工厂builder    @Autowired    private EntityManagerFactoryBuilder factoryBuilder;    /**     * 配置第一个实体管理工厂的bean     * @return     */    @Bean(name = "firstEntityManagerFactoryBean")    @Primary    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {        return factoryBuilder.dataSource(dataSource)                //这一行的目的是加入jpa的其他配置参数比如(ddl-auto: update等)                //当然这个参数配置可以在事务配置的时候也可以                .properties(jpaProperties.getHibernateProperties(new HibernateSettings()))                .packages("com.cetc.domain.first")                .persistenceUnit("firstPersistenceUnit")                .build();    }    /**     * EntityManager不过解释,用过jpa的应该都了解     * @return     */    @Bean(name = "firstEntityManager")    @Primary    public EntityManager entityManager() {        return entityManagerFactoryBean().getObject().createEntityManager();    }    /**     * jpa事务管理     * @return     */    @Bean(name = "firstTransactionManager")    @Primary    public JpaTransactionManager transactionManager() {        JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();        jpaTransactionManager.setEntityManagerFactory(entityManagerFactoryBean().getObject());        return jpaTransactionManager;    }}

3. JpaSecondConfiguration

package com.cetc.config;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.boot.autoconfigure.domain.EntityScan;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.annotation.EnableTransactionManagement;import javax.persistence.EntityManager;import javax.sql.DataSource;/** * 第二个数据源,jpa的相关配置 */@Configuration@EntityScan(basePackages = "com.cetc.domain.second")//1、实体扫描//2、实体管理ref//3、事务管理@EnableJpaRepositories(        basePackages = "com.cetc.repository.second",        entityManagerFactoryRef = "secondEntityManagerFactoryBean",        transactionManagerRef = "secondTransactionManager")@EnableTransactionManagementpublic class JpaSecondConfiguration {    //第二个数据源,必须加Qualifier    @Autowired    @Qualifier("dataSourceSecond")    private DataSource dataSource;    //jpa其他参数配置    @Autowired    private JpaProperties jpaProperties;    //实体管理工厂builder    @Autowired    private EntityManagerFactoryBuilder factoryBuilder;    /**     * 配置第二个实体管理工厂的bean     * @return     */    @Bean(name = "secondEntityManagerFactoryBean")    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {        return factoryBuilder.dataSource(dataSource)                .properties(jpaProperties.getHibernateProperties(new HibernateSettings()))                .packages("com.cetc.domain.second")                .persistenceUnit("secondPersistenceUnit")                .build();    }    /**     * EntityManager不过解释,用过jpa的应该都了解     * @return     */    @Bean(name = "secondEntityManager")    public EntityManager entityManager() {        return entityManagerFactoryBean().getObject().createEntityManager();    }    /**     * jpa事务管理     * @return     */    @Bean(name = "secondTransactionManager")    public JpaTransactionManager transactionManager() {        JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();        jpaTransactionManager.setEntityManagerFactory(entityManagerFactoryBean().getObject());        return jpaTransactionManager;    }}

如果感觉小编写得不错,请素质三连:点赞+转发+关注。我会努力写出更好的作品分享给大家。更多JAVA进阶学习资料小编已打包好,可以关注私信找我领取哦!

标签: #spring 配置多数据源 #springboot多数据源配置