首頁 > Java > java教程 > 主體

如何配置 Spring Data JPA 以在 Spring Boot 應用程式中使用多個資料來源?

Linda Hamilton
發布: 2024-10-25 04:46:30
原創
103 人瀏覽過

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>
登入後複製
(第二個資料來源)
<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
<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>
登入後複製
(Entity)

(第一個資料來源的儲存庫)

<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
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!