首页 > Java > java教程 > 如何配置 Spring Data JPA 以在 Spring Boot 应用程序中使用多个数据源?

如何配置 Spring Data JPA 以在 Spring Boot 应用程序中使用多个数据源?

Linda Hamilton
发布: 2024-10-25 04:46:30
原创
206 人浏览过

How do you configure Spring Data JPA to use multiple data sources in a Spring Boot application?

Spring Boot、具有多个数据源的 Spring Data JPA

在 Spring Boot 中,使用多个数据源允许将不同的存储库连接到单独的数据源。为了实现这一点,我们使用注释和配置来指定每个存储库的数据源和事务管理器。

Configuration

CustomerDataSourceConfiguration.java (第一个数据源)

<code class="java">@Configuration
@EnableJpaRepositories(
        entityManagerFactoryRef = "customerEntityManager",
        transactionManagerRef = "customerTransactionManager",
        basePackages = {"com.mm.repository.customer"})
public class CustomerDataSourceConfiguration {

    @Bean(name = "customerDataSource")
    public DataSource dataSource() {
        return DataSourceBuilder.create()
                .url("jdbc:h2:mem:customer:H2")
                .driverClassName("org.h2.Driver")
                .username("sa")
                .password("")
                .build();
    }

    @Bean(name = "customerEntityManager")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource());
        em.setPackagesToScan(new String[] {"com.mm.domain.customer"});

        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        em.setJpaProperties(additionalJpaProperties());
        em.setPersistenceUnitName("customerPersistence");
        em.setPackagesToScan("com.mm.domain.customer");

        return em;
    }

    Properties additionalJpaProperties() {
        Properties properties = new Properties();
        properties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
        properties.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
        properties.setProperty("hibernate.show_sql", "true");

        return properties;
    }

    @Bean(name = "customerTransactionManager")
    public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(emf);

        return transactionManager;
    }
}</code>
登录后复制

GenericDataSourceConfiguration.java(第二个数据源)

<code class="java">@Configuration
@EnableJpaRepositories(
        entityManagerFactoryRef = "genericEntityManager",
        transactionManagerRef = "genericTransactionManager",
        basePackages = {"com.mm.repository.generic"})
public class GenericDataSourceConfiguration {

    @Bean(name = "genericDataSource")
    public DataSource dataSource() {
        return DataSourceBuilder.create()
                .url("jdbc:h2:mem:generic:H2")
                .driverClassName("org.h2.Driver")
                .username("sa")
                .password("")
                .build();
    }

    @Bean(name = "genericEntityManager")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource());
        em.setPackagesToScan(new String[] {"com.mm.domain.generic"});

        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        em.setJpaProperties(additionalJpaProperties());
        em.setPersistenceUnitName("genericPersistence");
        em.setPackagesToScan("com.mm.domain.generic");

        return em;
    }

    Properties additionalJpaProperties() {
        Properties properties = new Properties();
        properties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
        properties.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
        properties.setProperty("hibernate.show_sql", "true");

        return properties;
    }

    @Bean(name = "genericTransactionManager")
    public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(emf);

        return transactionManager;
    }
}</code>
登录后复制

Application.java

<code class="java">@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application extends SpringApplication {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public ServletRegistrationBean h2Console() {
        ServletRegistrationBean reg = new ServletRegistrationBean(new WebServlet(), "/console/*");
        reg.setLoadOnStartup(1);
        return reg;
    }
}</code>
登录后复制

实体和存储库

Customer.java(实体)

<code class="java">@Entity
@Table(name = "customer")
@Data
@EqualsAndHashCode(exclude = {"id"})
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @Column(name = "name", nullable = false)
    private String name;

    @Column(name = "age", nullable = false)
    private Integer age;

    ....
}</code>
登录后复制

Order.java ( Entity)

<code class="java">@Entity
@Table(name = "order")
@Data
@EqualsAndHashCode(exclude = {"id"})
public class Order {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @Column(name = "code", nullable = false)
    private Integer code;

    @Column(name = "quality", nullable = false)
    private Integer quality;
}</code>
登录后复制

CustomerRepository.java(第一个数据源的存储库)

<code class="java">public interface CustomerRepository extends JpaRepository<Customer, Integer> {}</code>
登录后复制

GenericRepository.java(第二个数据的存储库)源)

<code class="java">public interface GenericRepository extends JpaRepository<Generic, Integer> {}</code>
登录后复制

通过使用这种方法,Spring Data JPA 将为每个数据源创建单独的 EntityManagerFactories 和 TransactionManager,从而实现与 Spring Boot 应用程序中的多个数据库的无缝集成。

以上是如何配置 Spring Data JPA 以在 Spring Boot 应用程序中使用多个数据源?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板