Spring Data與多數據源配置
大家好,我是免費搭建查券返利機器人省錢賺傭金就用微賺淘客系統3.0的小編,也是冬天不穿秋褲,天冷也要風度的程序猿!今天我們來探討如何在Spring Data中配置和使用多個數據源。
在現代應用程序中,處理多個數據源變得越來越常見。可能因為不同的數據存儲需求,例如讀寫分離、跨系統數據訪問,或者集成多個數據庫系統。本文將詳細講解如何在Spring Boot中使用Spring Data配置多個數據源,并提供具體的Java代碼示例。
一、項目依賴
首先,我們需要在pom.xml
中添加Spring Boot、Spring Data JPA以及數據庫驅動的依賴。
<dependencies><!-- Spring Boot Starter Data JPA --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><!-- H2 Database --><dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId></dependency><!-- MySQL Database --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency>
</dependencies>
二、配置多數據源
我們將配置兩個數據源:一個用于H2數據庫,另一個用于MySQL數據庫。
1. 配置文件
在application.yml
中配置數據源信息。
spring:datasource:h2:url: jdbc:h2:mem:testdbdriver-class-name: org.h2.Driverusername: sapassword: passwordmysql:url: jdbc:mysql://localhost:3306/testdbdriver-class-name: com.mysql.cj.jdbc.Driverusername: rootpassword: passwordjpa:hibernate:ddl-auto: updateshow-sql: trueproperties:hibernate:dialect: org.hibernate.dialect.H2Dialectformat_sql: true
2. 數據源配置類
我們需要為每個數據源創建單獨的配置類。
package cn.juwatech.config;import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;@Configuration
@EnableTransactionManagement
public class DataSourceConfig {@Primary@Bean(name = "h2DataSource")@ConfigurationProperties(prefix = "spring.datasource.h2")public DataSource h2DataSource() {return DataSourceBuilder.create().build();}@Bean(name = "mysqlDataSource")@ConfigurationProperties(prefix = "spring.datasource.mysql")public DataSource mysqlDataSource() {return DataSourceBuilder.create().build();}@Primary@Bean(name = "h2EntityManagerFactory")public LocalContainerEntityManagerFactoryBean h2EntityManagerFactory(@Qualifier("h2DataSource") DataSource dataSource) {LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();em.setDataSource(dataSource);em.setPackagesToScan("cn.juwatech.model.h2");em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());em.setPersistenceUnitName("h2PU");return em;}@Bean(name = "mysqlEntityManagerFactory")public LocalContainerEntityManagerFactoryBean mysqlEntityManagerFactory(@Qualifier("mysqlDataSource") DataSource dataSource) {LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();em.setDataSource(dataSource);em.setPackagesToScan("cn.juwatech.model.mysql");em.setJpaVendorAdapter(new HibernateJpaVendorAdapter());em.setPersistenceUnitName("mysqlPU");return em;}@Primary@Bean(name = "h2TransactionManager")public PlatformTransactionManager h2TransactionManager(@Qualifier("h2EntityManagerFactory") EntityManagerFactory entityManagerFactory) {return new JpaTransactionManager(entityManagerFactory);}@Bean(name = "mysqlTransactionManager")public PlatformTransactionManager mysqlTransactionManager(@Qualifier("mysqlEntityManagerFactory") EntityManagerFactory entityManagerFactory) {return new JpaTransactionManager(entityManagerFactory);}
}
3. 啟用JPA倉庫
為每個數據源分別配置JPA倉庫。
package cn.juwatech.config;import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;@Configuration
@EnableJpaRepositories(basePackages = "cn.juwatech.repository.h2",entityManagerFactoryRef = "h2EntityManagerFactory",transactionManagerRef = "h2TransactionManager"
)
@EntityScan(basePackages = "cn.juwatech.model.h2")
public class H2DataSourceConfig {
}@Configuration
@EnableJpaRepositories(basePackages = "cn.juwatech.repository.mysql",entityManagerFactoryRef = "mysqlEntityManagerFactory",transactionManagerRef = "mysqlTransactionManager"
)
@EntityScan(basePackages = "cn.juwatech.model.mysql")
public class MysqlDataSourceConfig {
}
三、定義實體類
在不同的包中定義不同數據源的實體類。
package cn.juwatech.model.h2;import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;@Entity
public class H2Entity {@Id@GeneratedValue(strategy = GenerationType.AUTO)private Long id;private String name;// getters and setters
}
package cn.juwatech.model.mysql;import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;@Entity
public class MysqlEntity {@Id@GeneratedValue(strategy = GenerationType.AUTO)private Long id;private String name;// getters and setters
}
四、定義倉庫接口
為每個數據源定義對應的倉庫接口。
package cn.juwatech.repository.h2;import cn.juwatech.model.h2.H2Entity;
import org.springframework.data.jpa.repository.JpaRepository;public interface H2EntityRepository extends JpaRepository<H2Entity, Long> {
}
package cn.juwatech.repository.mysql;import cn.juwatech.model.mysql.MysqlEntity;
import org.springframework.data.jpa.repository.JpaRepository;public interface MysqlEntityRepository extends JpaRepository<MysqlEntity, Long> {
}
五、測試多數據源配置
最后,我們編寫一個測試類,驗證多數據源配置是否成功。
package cn.juwatech;import cn.juwatech.model.h2.H2Entity;
import cn.juwatech.model.mysql.MysqlEntity;
import cn.juwatech.repository.h2.H2EntityRepository;
import cn.juwatech.repository.mysql.MysqlEntityRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class MultiDataSourceApplication implements CommandLineRunner {@Autowiredprivate H2EntityRepository h2EntityRepository;@Autowiredprivate MysqlEntityRepository mysqlEntityRepository;public static void main(String[] args) {SpringApplication.run(MultiDataSourceApplication.class, args);}@Overridepublic void run(String... args) throws Exception {H2Entity h2Entity = new H2Entity();h2Entity.setName("H2 Entity");h2EntityRepository.save(h2Entity);MysqlEntity mysqlEntity = new MysqlEntity();mysqlEntity.setName("MySQL Entity");mysqlEntityRepository.save(mysqlEntity);System.out.println("H2 Entities: " + h2EntityRepository.findAll());System.out.println("MySQL Entities: " + mysqlEntityRepository.findAll());}
}
總結
通過本文的介紹,我們展示了如何在Spring Data中配置和使用多個數據源。我們首先配置了數據源,然后為每個數據源創建了單獨的配置類和JPA倉庫,最后驗證了多數據源配置的正確性。這個示例展示了Spring Boot在處理多數據源時的靈活性和強大功能,希望對大家有所幫助。