如何使Spring Data处理多个异构数据源?

如何使Spring Data处理多个异构数据源?,第1张

如何使Spring Data处理多个异构数据源

您可以创建两个数据源和实体管理器,其中一个标记为@Primary

@Configuration@EnableJpaRepositories(basePackages = "io.eddumelendez.springdatajpa.repository1")public class FirstConfiguration {    @ConfigurationProperties(prefix = "datasource.postgres")    @Bean    @Primary    public DataSource postgresDataSource() {        return DataSourceBuilder.create().     build();    }    @Bean(name = "entityManagerFactory")    @Primary    public LocalContainerEntityManagerFactoryBean emf1(EntityManagerFactoryBuilder builder){        return builder     .dataSource(postgresDataSource())     .packages("io.eddumelendez.springdatajpa.domain1")     .persistenceUnit("users")     .build();    }}

另一个数据源的配置:

@Configuration@EnableJpaRepositories(basePackages = "io.eddumelendez.springdatajpa.repository2", entityManagerFactoryRef = "emf2")public class SecondConfiguration {    @Bean    @ConfigurationProperties(prefix = "datasource.mysql")    public DataSource mysqlDataSource() {        return DataSourceBuilder.create().build();    }    @Bean    public LocalContainerEntityManagerFactoryBean emf2(EntityManagerFactoryBuilder builder){        return builder     .dataSource(mysqlDataSource())     .packages("io.eddumelendez.springdatajpa.domain2")     .persistenceUnit("customers")     .build();    }}

您的application.properties应该如下所示:

datasource.mysql.url=jdbc:mysql://localhost:3306/mysql_demodatasource.mysql.username=rootdatasource.mysql.password=rootdatasource.postgres.url=jdbc:postgresql://localhost:5432/postgres_demodatasource.postgres.username=postgresdatasource.postgres.password=postgres


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5641562.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-16
下一篇2022-12-16

发表评论

登录后才能评论

评论列表(0条)

    保存