SpringBoot项目中的多数据源支持的方法
1.概述
项目中经常会遇到一个应用需要访问多个数据源的情况,本文介绍在SpringBoot项目中利用SpringDataJpa技术如何支持多个数据库的数据源。
具体的代码参照该示例项目
2.建立实体类(Entity)
首先,我们创建两个简单的实体类,分别属于两个不同的数据源,用于演示多数据源数据的保存和查询。
Test实体类:
packagecom.example.demo.test.data;
importjavax.persistence.Entity;
importjavax.persistence.Id;
importjavax.persistence.Table;
@Entity
@Table(name="test")
publicclassTest{
@Id
privateIntegerid;
publicTest(){
}
publicIntegergetId(){
returnthis.id;
}
publicvoidsetId(Integerid){
this.id=id;
}
}
Other实体类:
packagecom.example.demo.other.data;
importjavax.persistence.Entity;
importjavax.persistence.Id;
importjavax.persistence.Table;
@Entity
@Table(name="other")
publicclassOther{
@Id
privateIntegerid;
publicIntegergetId(){
returnthis.id;
}
publicvoidsetId(Integerid){
this.id=id;
}
}
需要注意的是,这两个实体类分属于不同的package,这一点极为重要,spring会根据实体类所属的package来决定用那一个数据源进行操作。
3.建立Repository
分别建立两个实体类对应的Repository,用于进行数据操作。
TestRepository:
packagecom.example.demo.test.data; importorg.springframework.data.jpa.repository.JpaRepository; publicinterfaceTestRepositoryextendsJpaRepository{ }
OtherRepository:
packagecom.example.demo.other.data; importorg.springframework.data.jpa.repository.JpaRepository; publicinterfaceOtherRepositoryextendsJpaRepository{ }
得益于spring-data-jpa优秀的封装,我们只需创建一个接口,就拥有了对实体类的操作能力。
3.对多数据源进行配置
分别对Test和Other两个实体类配置对应的数据源。配置的内容主要包含三个要素:
- dataSource,数据源的连接信息
- entityManagerFactory,数据处理
- transactionManager,事务管理
Test实体类的数据源配置TestDataConfig:
packagecom.example.demo.config;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.beans.factory.annotation.Qualifier;
importorg.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
importorg.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
importorg.springframework.boot.context.properties.ConfigurationProperties;
importorg.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
importorg.springframework.context.annotation.Bean;
importorg.springframework.context.annotation.Configuration;
importorg.springframework.context.annotation.Primary;
importorg.springframework.data.jpa.repository.config.EnableJpaRepositories;
importorg.springframework.orm.jpa.JpaTransactionManager;
importorg.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
importorg.springframework.transaction.PlatformTransactionManager;
importorg.springframework.transaction.annotation.EnableTransactionManagement;
importjavax.persistence.EntityManagerFactory;
importjavax.sql.DataSource;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef="entityManagerFactory",
basePackages={"com.example.demo.test.data"}
)
publicclassTestDataConfig{
@Autowired
privateJpaPropertiesjpaProperties;
@Primary
@Bean(name="dataSource")
@ConfigurationProperties(prefix="spring.datasource")
publicDataSourcedataSource(){
returnDataSourceBuilder.create().build();
}
@Primary
@Bean(name="entityManagerFactory")
publicLocalContainerEntityManagerFactoryBeanentityManagerFactory(
EntityManagerFactoryBuilderbuilder,
@Qualifier("dataSource")DataSourcedataSource){
returnbuilder
.dataSource(dataSource)
.packages("com.example.demo.test.data")
.properties(jpaProperties.getHibernateProperties(dataSource))
.persistenceUnit("test")
.build();
}
@Primary
@Bean(name="transactionManager")
publicPlatformTransactionManagertransactionManager(
@Qualifier("entityManagerFactory")EntityManagerFactoryentityManagerFactory){
returnnewJpaTransactionManager(entityManagerFactory);
}
}
代码中的Primary注解表示这是默认数据源。
Other实体类的数据源配置OtherDataConfig:
packagecom.example.demo.config;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.beans.factory.annotation.Qualifier;
importorg.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
importorg.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
importorg.springframework.boot.context.properties.ConfigurationProperties;
importorg.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
importorg.springframework.context.annotation.Bean;
importorg.springframework.context.annotation.Configuration;
importorg.springframework.data.jpa.repository.config.EnableJpaRepositories;
importorg.springframework.orm.jpa.JpaTransactionManager;
importorg.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
importorg.springframework.transaction.PlatformTransactionManager;
importorg.springframework.transaction.annotation.EnableTransactionManagement;
importjavax.persistence.EntityManagerFactory;
importjavax.sql.DataSource;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef="otherEntityManagerFactory",
transactionManagerRef="otherTransactionManager",
basePackages={"com.example.demo.other.data"}
)
publicclassOtherDataConfig{
@Autowired
privateJpaPropertiesjpaProperties;
@Bean(name="otherDataSource")
@ConfigurationProperties(prefix="other.datasource")
publicDataSourceotherDataSource(){
returnDataSourceBuilder.create().build();
}
@Bean(name="otherEntityManagerFactory")
publicLocalContainerEntityManagerFactoryBeanotherEntityManagerFactory(
EntityManagerFactoryBuilderbuilder,
@Qualifier("otherDataSource")DataSourceotherDataSource){
returnbuilder
.dataSource(otherDataSource)
.packages("com.example.demo.other.data")
.properties(jpaProperties.getHibernateProperties(otherDataSource))
.persistenceUnit("other")
.build();
}
@Bean(name="otherTransactionManager")
publicPlatformTransactionManagerotherTransactionManager(
@Qualifier("otherEntityManagerFactory")EntityManagerFactoryotherEntityManagerFactory){
returnnewJpaTransactionManager(otherEntityManagerFactory);
}
}
3.数据操作
我们创建一个Service类TestService来分别对两个数据源进行数据的操作。
packagecom.example.demo.service;
importcom.example.demo.other.data.Other;
importcom.example.demo.other.data.OtherRepository;
importcom.example.demo.test.data.Test;
importcom.example.demo.test.data.TestRepository;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.beans.factory.annotation.Value;
importorg.springframework.stereotype.Component;
@Component
publicclassTestService{
@Autowired
privateTestRepositorytestRepository;
@Autowired
privateOtherRepositoryotherRepository;
@Value("${name:World}")
privateStringname;
publicStringgetHelloMessage(){
Testtest=newTest();
test.setId(1);
test=testRepository.save(test);
Otherother=newOther();
other.setId(2);
other=otherRepository.save(other);
return"Hello"+this.name+":test'svalue="+test.getId()+",other'svalue="+other.getId();
}
}
对Test和Other分别进行数据插入和读取操作,程序运行后会打印出两个数据源各自的数据。数据库采用的mysql,连接信息在application.yml进行配置。
spring: datasource: url:jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&useSSL=false testWhileIdle:true validationQuery:SELECT1fromdual username:test password:11111111 driverClassName:com.mysql.jdbc.Driver jpa: database:MYSQL show-sql:true hibernate: show-sql:true ddl-auto:create naming-strategy:org.hibernate.cfg.ImprovedNamingStrategy properties: hibernate.dialect:org.hibernate.dialect.MySQL5Dialect other: datasource: url:jdbc:mysql://localhost:3306/other?characterEncoding=utf-8&useSSL=false testWhileIdle:true validationQuery:SELECT1 username:other password:11111111 driverClassName:com.mysql.jdbc.Driver jpa: database:MYSQL show-sql:true hibernate: show-sql:true ddl-auto:create naming-strategy:org.hibernate.cfg.ImprovedNamingStrategy properties: hibernate.dialect:org.hibernate.dialect.MySQL5Dialect
Test实体对应的是主数据源,采用了spring-boot的默认数据源配置项,Other实体单独配置数据源连接。具体应该读取哪一段配置内容,是在配置类OtherDataConfig中这行代码指定的。
@ConfigurationProperties(prefix="other.datasource")
本示例需要建立的数据库用户和库可以通过以下命令处理:
CREATEUSER'test'@'localhost'IDENTIFIEDBY'11111111'; GRANTALLPRIVILEGESON*.*TO'test'@'localhost'; CREATEUSER'other'@'localhost'IDENTIFIEDBY'11111111'; GRANTALLPRIVILEGESON*.*TO'other'@'localhost'; createdatabasetest; createdatabaseother;
4.总结
spring-data-jpa极大的简化了数据库操作,对于多数据源的支持,也只是需要增加一下配置文件和配置类而已。其中的关键内容有3点:
- 配置文件中数据源的配置
- 配置类的编写
- 实体类所在的package必须与配置类中指定的package一致,如OtherDataConfig中指定的basePackages={"com.example.demo.other.data"}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。