springboot+jpa 实现不同数据库的多数据源配置

首页 / 新闻资讯 / 正文

废话不多说,直接看配置!

1、application.yml

# 多数据源配置 #primary spring:   primary:     datasource:       url: jdbc:mysql://xxx.xxx.xxx.xxx:3306/dico_dev?autoReconnect=true&autoReconnectForPools=true&useUnicode=true&characterEncoding=UTF-8&useSSL=true       username: root       password: xxxx       driver-class-name: com.mysql.jdbc.Driver  #secondary   secondary:     datasource:       url: jdbc:sqlserver://xxx.xxx.xxxx.xxx:1433;databasename=LZMISportal       username: root       password: xxxx       driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver    jpa:     hibernate:       primary-dialect: org.hibernate.dialect.MySQL5Dialect       secondary-dialect: org.hibernate.dialect.SQLServer2008Dialect     open-in-view: true     show-sql: true

配置文件如上,分别定义两个数据库的链接和数据库对应的方言。

2、配置数据源

@Configuration public class DataSourceConfig {       @Bean(name = "primaryDataSource")     @Primary     @Qualifier("primaryDataSource")     @ConfigurationProperties(prefix = "spring.primary.datasource")     public DataSource primaryDatasource() {         return DataSourceBuilder.create().build();     }      @Bean(name = "secondaryDataSource")     @Qualifier("secondaryDataSource")     @ConfigurationProperties(prefix = "spring.secondary.datasource")     public DataSource secondaryDataSource() {         return DataSourceBuilder.create().build();     }  }

代码解析:1、两个数据源分别对应yml文件中配置的数据源 2、使用@Bean注解将对应方法发布以供后边使用

3、定义不同数据源的作用域

多数据源配置 1)

@Configuration @EnableTransactionManagement @EnableJpaRepositories(         entityManagerFactoryRef = "entityManagerFactoryPrimary",//配置连接工厂 entityManagerFactory         transactionManagerRef = "transactionManagerPrimary", //配置 事物管理器  transactionManager         basePackages = {"xxx.xxx.xxx.xxx","xxx.xxx.xxx.xxx","xxx.xxx.xxx.xxx","xxx.xxx.xxx.xxx","xxx.xxx.xxx.xxx"}//设置持久层所在位置 ) public class PrimaryConfig {      @Autowired     private JpaProperties jpaProperties;      @Autowired     @Qualifier("primaryDataSource")     private DataSource primaryDataSource;// 自动注入配置好的数据源          @Value("${spring.jpa.hibernate.primary-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("xxx.xxx.xxx.xxx","xxx.xxx.xxx.xxx","xxx.xxx.xxx.xxx","xxx.xxx.xxx.xxx","xxx.xxx.xxx.xxx")                 // 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.setProperties(map);         return jpaProperties.getHibernateProperties(dataSource);     }      /**      * 配置事物管理器      *      * @param builder      * @return      */     @Bean(name = "transactionManagerPrimary")     @Primary     PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {         return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());     }   }

多数据源配置 2)

@Configuration @EnableTransactionManagement @EnableJpaRepositories(         entityManagerFactoryRef="entityManagerFactorySecondary",         transactionManagerRef="transactionManagerSecondary",         basePackages= { "xxx.xxx.xxx.xxx" }) public class SecondaryConfig {      @Autowired     private JpaProperties jpaProperties;      @Autowired     @Qualifier("secondaryDataSource")     private DataSource secondaryDataSource;          @Value("${spring.jpa.hibernate.secondary-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("xxx.xxx.xxx.xxx")                 .persistenceUnit("secondaryPersistenceUnit")                 .build();     }      private Map<String, String> getVendorProperties(DataSource dataSource) {         Map<String,String> map = new HashMap<>();         map.put("hibernate.dialect",secondaryDialect);         jpaProperties.setProperties(map);         return jpaProperties.getHibernateProperties(dataSource);     }      @Bean(name = "transactionManagerSecondary")     PlatformTransactionManager transactionManagerSecondary(EntityManagerFactoryBuilder builder) {         return new JpaTransactionManager(entityManagerFactorySecondary(builder).getObject());     }   }

至此,所有配置已完成,配置扫描到的所有@Entity类将被对应到不同的数据库中。