Spring Boot整合JPA使用多个数据源的方法步骤
介绍
JPA(JavaPersistenceAPI)Java持久化API,是Java持久化的标准规范,Hibernate是持久化规范的技术实现,而SpringDataJPA是在Hibernate基础上封装的一款框架。
第一次使用SpringJPA的时候,感觉这东西简直就是神器,几乎不需要写什么关于数据库访问的代码一个基本的CURD的功能就出来了。在这篇文章中,我们将介绍SpringBoot整合JPA使用多个数据源的方法。
开发环境:
- SpringBoot2.0.5
- SpringDataJPA2.0.5
- MySQL5.6
- JDK8
- IDEA2018.3
- Windows10
引入依赖
首先我们要SpringBoot引入spring-boot-starter-data-jpa依赖。
Maven配置:
org.springframework.boot spring-boot-starter-data-jpa org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-devtools runtime mysql mysql-connector-java runtime
Gradle配置:
compilegroup:'org.springframework.boot',name:'spring-boot-starter-data-jpa',version:'2.0.5.RELEASE' compilegroup:'org.springframework.boot',name:'spring-boot-starter-web',version:'2.0.5.RELEASE' compilegroup:'org.springframework.boot',name:'spring-boot-devtools',version:'2.0.5.RELEASE' compilegroup:'mysql',name:'mysql-connector-java',version:'6.0.6'
配置数据源
SpringBoot提供了使用application.properties或application.yml文件配置项目属性的方法。我比较习惯使用application.yml文件,所以这里我只列出application.yml文件的写法。
spring: datasource: product: driver-class-name:com.mysql.jdbc.Driver jdbc-url:jdbc:mysql://127.0.0.1:3306/product?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull username:root password:test123$ customer: driver-class-name:com.mysql.jdbc.Driver jdbc-url:jdbc:mysql://127.0.0.1:3306/customer?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull username:root password:test123$ jpa: generate-ddl:true
配置好application.yml文件后分别在数据库创建customer和product数据库。
添加实体(Entity)类
客户实体:
packagecom.springboot.jpa.customer.models;
importjavax.persistence.*;
@Entity
publicclassCustomer{
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
privateIntegerid;
@Column(unique=true,nullable=false)
privateStringemail;
privateStringfirstName;
privateStringlastName;
protectedCustomer(){
}
publicCustomer(Stringemail,StringfirstName,StringlastName){
this.email=email;
this.firstName=firstName;
this.lastName=lastName;
}
@Override
publicStringtoString(){
returnString.format("Customer[id=%d,firstName='%s',lastName='%s',email='%s']",id,firstName,lastName,email);
}
publicIntegergetId(){
returnid;
}
publicStringgetEmail(){
returnemail;
}
publicStringgetFirstName(){
returnfirstName;
}
publicStringgetLastName(){
returnlastName;
}
}
产品实体:
packagecom.springboot.jpa.product.models;
importjavax.persistence.*;
@Entity
publicclassProduct{
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
privateintid;
@Column(nullable=false)
privateStringcode;
privateStringname;
privatedoubleprice;
protectedProduct(){
}
publicProduct(Stringcode,Stringname,doubleprice){
this.code=code;
this.name=name;
this.price=price;
}
@Override
publicStringtoString(){
returnString.format("Product[id=%d,code='%s',name='%s',price='%s']",id,code,name,price);
}
publicintgetId(){
returnid;
}
publicStringgetCode(){
returncode;
}
publicStringgetName(){
returnname;
}
publicdoublegetPrice(){
returnprice;
}
}
添加数据仓库(Repository)类
客户Repository:
packagecom.springboot.jpa.customer.repository; importcom.springboot.jpa.customer.models.Customer; importorg.springframework.data.jpa.repository.JpaRepository; importorg.springframework.stereotype.Repository; @Repository publicinterfaceCustomerRepositoryextendsJpaRepository{ }
产品Repository:
packagecom.springboot.jpa.product.repository; importcom.springboot.jpa.product.models.Product; importorg.springframework.data.jpa.repository.JpaRepository; importorg.springframework.stereotype.Repository; @Repository publicinterfaceProductRepositoryextendsJpaRepository{ }
添加配置(Config)类
客户配置:
packagecom.springboot.jpa.customer.config;
importorg.springframework.beans.factory.annotation.Qualifier;
importorg.springframework.boot.context.properties.ConfigurationProperties;
importorg.springframework.boot.jdbc.DataSourceBuilder;
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="customerEntityManagerFactory",transactionManagerRef="customerTransactionManager",basePackages={"com.springboot.jpa.customer.repository"})
publicclassCustomerConfig{
@Primary
@Bean(name="customerDataSource")
@ConfigurationProperties(prefix="spring.datasource.customer")
publicDataSourcecustomerDataSource(){
returnDataSourceBuilder.create().build();
}
@Primary
@Bean(name="customerEntityManagerFactory")
publicLocalContainerEntityManagerFactoryBeanentityManagerFactory(EntityManagerFactoryBuilderbuilder,@Qualifier("customerDataSource")DataSourcedataSource){
returnbuilder.dataSource(dataSource).packages("com.springboot.jpa.customer.models").persistenceUnit("customer").build();
}
@Primary
@Bean(name="customerTransactionManager")
publicPlatformTransactionManagercustomerTransactionManager(@Qualifier("customerEntityManagerFactory")EntityManagerFactorycustomerEntityManagerFactory){
returnnewJpaTransactionManager(customerEntityManagerFactory);
}
}
产品配置:
packagecom.springboot.jpa.product.config;
importorg.springframework.beans.factory.annotation.Qualifier;
importorg.springframework.boot.context.properties.ConfigurationProperties;
importorg.springframework.boot.jdbc.DataSourceBuilder;
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="productEntityManagerFactory",transactionManagerRef="productTransactionManager",basePackages={"com.springboot.jpa.product.repository"}
)
publicclassProductConfig{
@Bean(name="productDataSource")
@ConfigurationProperties(prefix="spring.datasource.product")
publicDataSourcedataSource(){
returnDataSourceBuilder.create().build();
}
@Bean(name="productEntityManagerFactory")
publicLocalContainerEntityManagerFactoryBeanbarEntityManagerFactory(EntityManagerFactoryBuilderbuilder,@Qualifier("productDataSource")DataSourcedataSource){
returnbuilder.dataSource(dataSource).packages("com.springboot.jpa.product.models").persistenceUnit("product").build();
}
@Bean(name="productTransactionManager")
publicPlatformTransactionManagerproductTransactionManager(@Qualifier("productEntityManagerFactory")EntityManagerFactoryproductEntityManagerFactory){
returnnewJpaTransactionManager(productEntityManagerFactory);
}
}
项目结构:
src/main/java
-com.springboot.jpa
-product
-config
-models
-repository
-customer
-config
-models
-repository
添加测试类
客户测试类CustomerDataSourcesTests:
packagecom.springboot.jpa;
importcom.springboot.jpa.customer.repository.CustomerRepository;
importcom.springboot.jpa.customer.models.Customer;
importorg.junit.runner.RunWith;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.boot.test.context.SpringBootTest;
importorg.springframework.test.context.junit4.SpringRunner;
importorg.springframework.transaction.annotation.Transactional;
importorg.junit.Test;
importstaticorg.junit.Assert.assertEquals;
importstaticorg.junit.Assert.assertNotNull;
@RunWith(SpringRunner.class)
@SpringBootTest
publicclassCustomerDataSourcesTests{
@Autowired
privateCustomerRepositorycustomerRepository;
@Test
@Transactional("customerTransactionManager")
publicvoidcreateCustomer(){
Customercustomer=newCustomer("master@weilog.net","Charles","Zhang");
customer=customerRepository.save(customer);
assertNotNull(customerRepository.findById(customer.getId()));
assertEquals(customerRepository.findById(customer.getId()).get().getEmail(),"master@weilog.net");
}
}
产品测试类ProductDataSourcesTests:
packagecom.springboot.jpa;
importcom.springboot.jpa.product.models.Product;
importcom.springboot.jpa.product.repository.ProductRepository;
importorg.junit.runner.RunWith;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.boot.test.context.SpringBootTest;
importorg.springframework.test.context.junit4.SpringRunner;
importorg.springframework.transaction.annotation.Transactional;
importorg.junit.Test;
importstaticorg.junit.Assert.assertNotNull;
@RunWith(SpringRunner.class)
@SpringBootTest
publicclassProductDataSourcesTests{
@Autowired
privateProductRepositoryproductRepository;
@Test
@Transactional("productTransactionManager")
publicvoidcreateProduct(){
Productproduct=newProduct("10000","Book",80.0);
product=productRepository.save(product);
assertNotNull(productRepository.findById(product.getId()));
}
}
测试
分别运行两个测试类通过后,查询数据库。
客户表:
mysql>SELECT*FROMcustomer; +----+-------------------+-----------+----------+ |id|email|firstName|lastName| +----+-------------------+-----------+----------+ |1|master@weilog.net|Charles|Zhang| +----+-------------------+-----------+----------+ 1rowinset
产品表:
mysql>SELECT*FROMproduct; +----+-------+------+-------+ |id|code|name|price| +----+-------+------+-------+ |1|10000|Book|80| +----+-------+------+-------+ 1rowinset
本文地址:SpringBoot整合JPA使用多个数据源
项目地址:spring-boot-jpa
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对毛票票的支持。