Home > Java > javaTutorial > body text

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

Linda Hamilton
Release: 2024-10-25 04:46:30
Original
103 people have browsed it

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

Spring Boot, Spring Data JPA with Multiple DataSources

In Spring Boot, using multiple data sources allows for connecting different repositories to separate data sources. To achieve this, we use annotations and configurations to specify the data source and transaction manager for each repository.

Configuration

CustomerDataSourceConfiguration.java (First Data Source)

<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>
Copy after login

GenericDataSourceConfiguration.java (Second Data Source)

<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>
Copy after login

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>
Copy after login

Entities and Repositories

Customer.java (Entity)

<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>
Copy after login

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>
Copy after login

CustomerRepository.java (Repository for First Data Source)

<code class="java">public interface CustomerRepository extends JpaRepository<Customer, Integer> {}</code>
Copy after login

GenericRepository.java (Repository for Second Data Source)

<code class="java">public interface GenericRepository extends JpaRepository<Generic, Integer> {}</code>
Copy after login

By using this approach, Spring Data JPA will create separate EntityManagerFactories and TransactionManagers for each data source, enabling seamless integration with multiple databases in a Spring Boot application.

The above is the detailed content of How do you configure Spring Data JPA to use multiple data sources in a Spring Boot application?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!