springboot:jpa 如何做多数据源

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_38750084/article/details/86707994

service:

1.配置里配置多个数据源

application.properties

spring.datasource.primary.url=
spring.datasource.primary.username=
spring.datasource.primary.password=
spring.datasource.primary.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.primary.max-idle=10
spring.datasource.primary.maximum-pool-size=100
spring.datasource.primary.max-wait=10000
spring.datasource.primary.min-idle=5
spring.datasource.primary.initial-size=5

2.不同数据源对应多个文件,以下举一个数据源例子作为说明 如

primary

上代码:

注意:只有一个主数据源,如果不是主数据源,配置下面这个文件时去掉primary那个标签即可。

package com.***.***.web.dao;

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.jdbc.DataSourceProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
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.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryPrimary",
        transactionManagerRef = "transactionManagerPrimary",
        basePackages = {"com.***.***.dao.**.repository"})          //指定dao路径,数据库操作
public class PrimaryDBConf {

    /**
     * 构建主数据源
     *
     * @return
     */
    @Bean
    @Primary  //只有一个主数据源,如果不是主数据源,这个标签要去掉!!!
    @Qualifier("primaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.primary")             //选择主数据源
    public DataSourceProperties primaryDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    @Primary  //只有一个主数据源,如果不是主数据源,这个标签要去掉!!!
    @Qualifier("primaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.primary")            //选择主数据源
    public DataSource primaryDataSource() {
        return primaryDataSourceProperties().initializeDataSourceBuilder().build();
    }

    @Autowired
    @Qualifier("primaryDataSource")
    private DataSource primaryDataSource;

    @Autowired
    private JpaProperties jpaProperties;

    /**
     * HibernateSettings为配置列名生成策略,在yml中已经配置
     * spring boot1.5.* 中此方法有区别。返回的是DataSource,详见spring-boot-examples下的spring-boot-multi-datasource示例
     *
     * @return
     */
    public Map<String, Object> getVerdorProperties() {
        return jpaProperties.getHibernateProperties(new HibernateSettings());
    }

    /**
     * entity管理工厂,指定entity位置
     *
     * @param builder
     * @return
     */
    @Primary   //只有一个主数据源,如果不是主数据源,这个标签要去掉!!!
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(primaryDataSource)
                .packages("com.***.***.dao.**.entity")          //指定entity路径,字段映射
                .properties(getVerdorProperties())
                .persistenceUnit("primaryPersistenceUnit")
                .build();
    }

    @Bean
    @Primary  //只有一个主数据源,如果不是主数据源,这个标签要去掉!!!
    public EntityManager entityManagerPrimary(EntityManagerFactoryBuilder builder) {
        return entityManagerFactoryPrimary(builder).getObject().createEntityManager();
    }

    @Primary  //只有一个主数据源,如果不是主数据源,这个标签要去掉!!!
    @Bean
    public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
    }
}

另一个参考:

package com.***.***.service.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
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.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryResume",
        transactionManagerRef = "transactionManagerResume",
        basePackages = {"com.***.***.dao.resume.repository"})          //指定dao路径,数据库操作
public class ResumeDBConf {

    /**
     * 构建简历数据源
     *
     * @return
     */
    @Bean
    @Qualifier("resumeDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.resume")             //选择主数据源
    public DataSourceProperties resumeDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    @Qualifier("resumeDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.resume")            //选择主数据源
    public DataSource resumeDataSource() {
        return resumeDataSourceProperties().initializeDataSourceBuilder().build();
    }

    @Autowired
    @Qualifier("resumeDataSource")
    private DataSource resumeDataSource;

    @Autowired
    private JpaProperties jpaProperties;

    /**
     * HibernateSettings为配置列名生成策略,在yml中已经配置
     * spring boot1.5.* 中此方法有区别。返回的是DataSource,详见spring-boot-examples下的spring-boot-multi-datasource示例
     *
     * @return
     */
    public Map<String, Object> getVerdorProperties() {
        return jpaProperties.getHibernateProperties(new HibernateSettings());
    }

    /**
     * entity管理工厂,指定entity位置
     *
     * @param builder
     * @return
     */
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryResume(EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(resumeDataSource)
                .packages("com.***.***.dao.resume.entity")          //指定entity路径,字段映射
                .properties(getVerdorProperties())
                .persistenceUnit("resumePersistenceUnit")
                .build();
    }

    @Bean
    public EntityManager entityManagerResume(EntityManagerFactoryBuilder builder) {
        return entityManagerFactoryResume(builder).getObject().createEntityManager();
    }

    @Bean
    public PlatformTransactionManager transactionManagerResume(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryResume(builder).getObject());
    }
}

以上即可,但是自己新增第二个数据源时遇到一个问题

因为第二个数据源的表名为大写,而hibernate做映射只识别小写,报错:

解决方式为:

1.配置文件增加如下

//如果配置为这个,可以识别表,但是不能将createTime-->create_time
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

2.新增类

代码:

package com.huayong.bi.service.dao;

import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy;

//如果需要映射字段,需要添加实现类
public class MySQLUpperCaseStrategy extends SpringPhysicalNamingStrategy {
    private static final long serialVersionUID = 1383021413247872469L;

    @Override
    public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment context) {
        //将小写表名转换为大写表名
        return Identifier.toIdentifier(name.getText().toUpperCase(),name.isQuoted());
    }
}

参考:https://www.jianshu.com/p/a2a7c1c26fb3

注意:可以新增多个数据源

web服务与service服务一样,都需要配置!

猜你喜欢

转载自blog.csdn.net/weixin_38750084/article/details/86707994
今日推荐