在本文中,我们将学习如何在一个典型的Spring Boot Web应用程序中配置多个数据源并连接到多个数据库。我们将使用Spring Boot 2.0.5
、JPA
、Hibernate 5
、Thymeleaf
和H2
数据库来构建一个简单的Spring Boot多数据源Web应用。
我们知道,如果你有一个单一的数据库,Spring Boot的自动配置是开箱即用的,并通过其属性提供大量的定制选项。但如果你的应用要求对应用配置有更多的控制,你可以关闭特定的自动配置,自己配置组件。
在这篇文章中,我们将逐步学习如何在同一个应用程序中使用多个数据库。如果我们需要连接多个数据库,我们需要配置各种Spring Bean,如DataSources
、TransactionManagers
、EntityManagerFactoryBeans
、DataSourceInitializers
等,明确配置。
我们将构建一个Spring Boot网络应用,其中security data
被存储在一个数据库/模式中,order-related data
被存储在另一个数据库/模式中。
让我们看看我们如何在Spring Boot中处理多个数据库,并使用基于Spring Data JPA的应用程序。
Spring Boot
- 2.0.5.RELEASEJDK
- 1.8或更高版本Spring Framework
- 5.0.9 RELEASESpring Data JPA
- 2.0.10 RELEASEHibernate
- 5.2.17.FinalMaven
- 3.2+JPA
H2
Thymeleaf
IDE
Eclipse 或 Spring Tool Suite (STS)有很多方法可以创建Spring Boot应用程序。最简单的方法是在http://start.spring.io/使用Spring Initializr,它是一个在线Spring Boot应用程序生成器。
看上面的图,我们指定了以下细节。
Generate
: Maven项目Java Version
: 1.8 (默认)Spring Boot
:2.0.4Group
: net.guards.springbootArtifact
: springboot-multiple-datasourcesName
: springboot-multiple-datasourcesDescription
: 一个简单的用户管理应用的Rest APIPackage Name
: net.guards.springboot.springbootmultipledatasourcesPackaging
: jar (这是默认值)Dependencies
: Web, JPA, H2, DevTools以下是项目结构 -
<?xmlversion="1.0"encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.guides.springboot</groupId>
<artifactId>springboot-multiple-datasources</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot-multiple-datasources</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
确保我们在classpath上有JPA
、Thymeleaf
和H2
启动器。
接下来的步骤非常重要,请看一下。
让我们关闭DataSource/JPA的自动配置功能。由于我们要明确配置数据库相关的bean,我们将通过排除AutoConfiguration
类来关闭DataSource/JPA的自动配置。
package net.guides.springboot.springbootmultipledatasources;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@SpringBootApplication(
exclude = { DataSourceAutoConfiguration.class,
HibernateJpaAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class })
@EnableTransactionManagement
public class SpringbootMultipleDatasourcesApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootMultipleDatasourcesApplication.class, args);
}
}
一旦我们关闭了自动配置,我们就需要通过使用@EnableTransactionManagement
注解来明确启用TransactionManagement。
让我们来配置H2
数据源属性。在application.properties
文件中配置安全和订单的数据库连接参数.
debug=true
datasource.security.driver-class-name=org.h2.Driver
datasource.security.url=jdbc:h2:mem:securitydb;DB_CLOSE_DELAY=-1
datasource.security.username=sa
datasource.security.password=
datasource.security.initialize=true
datasource.orders.driver-class-name=org.h2.Driver
datasource.orders.url=jdbc:h2:mem:ordersdb;DB_CLOSE_DELAY=-1
datasource.orders.username=sa
datasource.orders.password=
datasource.orders.initialize=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
我们使用H2
数据库来快速建立应用程序,但你也可以在application.properties
文件中替换以下配置来使用MySQL
数据库进行生产。
注意,我们使用了自定义属性键来配置两个数据源属性。
在下一步,我们将创建一个与安全相关的JPA实体和一个JPA资源库。
/**
*
*/
package net.guides.springboot.springbootmultipledatasources.security.entities;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* @author Ramesh Fadatare
*
*/
@Entity
@Table(name="USERS")
public class User
{
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
@Column(nullable=false)
private String name;
@Column(nullable=false, unique=true)
private String email;
private boolean disabled;
@OneToMany(mappedBy="user")
private Set<Address> addresses;
public User()
{
}
public User(Integer id, String name, String email)
{
this.id = id;
this.name = name;
this.email = email;
}
public User(Integer id, String name, String email, boolean disabled)
{
this.id = id;
this.name = name;
this.email = email;
this.disabled = disabled;
}
public Integer getId()
{
return id;
}
public void setId(Integer id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public boolean isDisabled()
{
return disabled;
}
public void setDisabled(boolean disabled)
{
this.disabled = disabled;
}
public Set<Address> getAddresses()
{
return addresses;
}
public void setAddresses(Set<Address> addresses)
{
this.addresses = addresses;
}
}
package net.guides.springboot.springbootmultipledatasources.security.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
* @author Ramesh Fadatare
*
*/
@Entity
@Table(name="ADDRESSES")
public class Address
{
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
@Column(nullable=false)
private String city;
@ManyToOne
@JoinColumn(name="user_id")
private User user;
public Integer getId()
{
return id;
}
public void setId(Integer id)
{
this.id = id;
}
public String getCity()
{
return city;
}
public void setCity(String city)
{
this.city = city;
}
public User getUser()
{
return user;
}
public void setUser(User user)
{
this.user = user;
}
}
/**
*
*/
package net.guides.springboot.springbootmultipledatasources.security.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import net.guides.springboot.springbootmultipledatasources.security.entities.User;
/**
* @author Ramesh Fadatare
*
*/
public interface UserRepository extends JpaRepository<User, Integer>
{
}
/**
*
*/
package net.guides.springboot.springbootmultipledatasources.orders.entities;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* @author Ramesh Fadatare
*
*/
@Entity
@Table(name="ORDERS")
public class Order
{
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
@Column(nullable=false, name="cust_name")
private String customerName;
@Column(nullable=false, name="cust_email")
private String customerEmail;
@OneToMany(mappedBy="order")
private Set<OrderItem> orderItems;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerEmail() {
return customerEmail;
}
public void setCustomerEmail(String customerEmail) {
this.customerEmail = customerEmail;
}
public Set<OrderItem> getOrderItems()
{
return orderItems;
}
public void setOrderItems(Set<OrderItem> orderItems)
{
this.orderItems = orderItems;
}
}
package net.guides.springboot.springbootmultipledatasources.orders.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
* @author Ramesh Fadatare
*
*/
@Entity
@Table(name="ORDER_ITEMS")
public class OrderItem
{
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String productCode;
private int quantity;
@ManyToOne
@JoinColumn(name="order_id")
private Order order;
public Integer getId()
{
return id;
}
public void setId(Integer id)
{
this.id = id;
}
public String getProductCode()
{
return productCode;
}
public void setProductCode(String productCode)
{
this.productCode = productCode;
}
public int getQuantity()
{
return quantity;
}
public void setQuantity(int quantity)
{
this.quantity = quantity;
}
public Order getOrder()
{
return order;
}
public void setOrder(Order order)
{
this.order = order;
}
}
/**
*
*/
package net.guides.springboot.springbootmultipledatasources.orders.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import net.guides.springboot.springbootmultipledatasources.orders.entities.Order;
/**
* @author Ramesh Fadatare
*
*/
public interface OrderRepository extends JpaRepository<Order, Integer>{
}
创建SQL脚本来初始化样本数据。在src/main/resources
文件夹中创建security-data.sql
脚本,用样本数据初始化USERS
表。
delete from addresses;
delete from users;
insert into users(id, name, email,disabled) values(1,'John Cena','john@gmail.com', false);
insert into users(id, name, email,disabled) values(2,'Salman Khan','salman@gmail.com', false);
insert into users(id, name, email,disabled) values(3,'Amitr Khan','amir@gmail.com', true);
insert into addresses(id,city,user_id) values(1, 'Pune',1);
insert into addresses(id,city,user_id) values(2, 'Landon',1);
insert into addresses(id,city,user_id) values(3, 'Newyork',2);
insert into addresses(id,city,user_id) values(4, 'Mumbai',3);
insert into addresses(id,city,user_id) values(6, 'Washington',3);
在src/main/resources
文件夹中创建orders-data.sql
脚本,用样本数据初始化ORDERS
表。
delete from order_items;
delete from orders;
insert into orders(id, cust_name, cust_email) values(1,'John Cena','john@gmail.com');
insert into orders(id, cust_name, cust_email) values(2,'Salman Khan','salman@gmail.com');
insert into orders(id, cust_name, cust_email) values(3,'Amir Khan','amir@gmail.com');
insert into order_items(id, productcode,quantity,order_id) values(1,'order item1', 2, 1);
insert into order_items(id, productcode,quantity,order_id) values(2,'order item2', 1, 1);
insert into order_items(id, productcode,quantity,order_id) values(3,'order item3', 5, 1);
insert into order_items(id, productcode,quantity,order_id) values(4,'order item4', 2, 2);
insert into order_items(id, productcode,quantity,order_id) values(5,'order item5', 1, 2);
创建SecurityDataSourceConfig.java
配置类。我们将通过连接SecurityDataSourceConfig.java
中的安全数据库来配置Spring Bean,如DataSource
、TransactionManager
、EntityManagerFactoryBean
和DataSourceInitializer
。
package net.guides.springboot.springbootmultipledatasources.config;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
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.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.init.DataSourceInitializer;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
/**
* @author Ramesh Fadatare
*
*/
@Configuration
@EnableJpaRepositories(
basePackages = "net.guides.springboot.springbootmultipledatasources.security.repositories",
entityManagerFactoryRef = "securityEntityManagerFactory",
transactionManagerRef = "securityTransactionManager"
)
public class SecurityDataSourceConfig
{
@Autowired
private Environment env;
@Bean
@ConfigurationProperties(prefix="datasource.security")
public DataSourceProperties securityDataSourceProperties() {
return new DataSourceProperties();
}
@Bean
public DataSource securityDataSource() {
DataSourceProperties securityDataSourceProperties = securityDataSourceProperties();
return DataSourceBuilder.create()
.driverClassName(securityDataSourceProperties.getDriverClassName())
.url(securityDataSourceProperties.getUrl())
.username(securityDataSourceProperties.getUsername())
.password(securityDataSourceProperties.getPassword())
.build();
}
@Bean
public PlatformTransactionManager securityTransactionManager()
{
EntityManagerFactory factory = securityEntityManagerFactory().getObject();
return new JpaTransactionManager(factory);
}
@Bean
public LocalContainerEntityManagerFactoryBean securityEntityManagerFactory()
{
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setDataSource(securityDataSource());
factory.setPackagesToScan(new String[]{"net.guides.springboot.springbootmultipledatasources.security.entities"});
factory.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
Properties jpaProperties = new Properties();
jpaProperties.put("hibernate.hbm2ddl.auto", env.getProperty("spring.jpa.hibernate.ddl-auto"));
jpaProperties.put("hibernate.show-sql", env.getProperty("spring.jpa.show-sql"));
factory.setJpaProperties(jpaProperties);
return factory;
}
@Bean
public DataSourceInitializer securityDataSourceInitializer()
{
DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
dataSourceInitializer.setDataSource(securityDataSource());
ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
databasePopulator.addScript(new ClassPathResource("security-data.sql"));
dataSourceInitializer.setDatabasePopulator(databasePopulator);
dataSourceInitializer.setEnabled(env.getProperty("datasource.security.initialize", Boolean.class, false));
return dataSourceInitializer;
}
}
请注意,你已经通过使用@ConfigurationProperties(prefix="datasource.security")
和DataSourceBuilder
流畅的API来创建DataSource
Bean,将datasource.security.* properties
填充到DataSourceProperties
中。
在创建LocalContainerEntityManagerFactoryBean
Bean时,你已经配置了名为net.guides.springboot.springbootmultipledatasources.security.entities
的包来扫描JPA实体。你已经配置了DataSourceInitializer
Bean来初始化来自security-data.sql的样本数据。
最后,我们通过使用@EnableJpaRepositories
注解来启用Spring Data JPA支持。由于我们将有多个EntityManagerFactory
和TransactionManager
豆,我们通过指向各自的豆名来配置entityManagerFactoryRef
和transactionManagerRef
的豆ID。我们还配置了basePackages属性,以指示在哪里寻找Spring Data JPA的仓库(包)。
创建OrdersDataSourceConfig.java
配置类。与SecurityDataSourceConfig.java
类似,你将创建OrdersDataSourceConfig.java
,但将其指向订单数据库。
package net.guides.springboot.springbootmultipledatasources.config;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
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.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.init.DataSourceInitializer;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
/**
* @author Ramesh Fadatare
*
*/
@Configuration
@EnableJpaRepositories(
basePackages = "net.guides.springboot.springbootmultipledatasources.orders.repositories",
entityManagerFactoryRef = "ordersEntityManagerFactory",
transactionManagerRef = "ordersTransactionManager"
)
public class OrdersDataSourceConfig {
@Autowired
private Environment env;
@Bean
@ConfigurationProperties(prefix = "datasource.orders")
public DataSourceProperties ordersDataSourceProperties() {
return new DataSourceProperties();
}
@Bean
public DataSource ordersDataSource() {
DataSourceProperties primaryDataSourceProperties = ordersDataSourceProperties();
return DataSourceBuilder.create()
.driverClassName(primaryDataSourceProperties.getDriverClassName())
.url(primaryDataSourceProperties.getUrl())
.username(primaryDataSourceProperties.getUsername())
.password(primaryDataSourceProperties.getPassword())
.build();
}
@Bean
public PlatformTransactionManager ordersTransactionManager() {
EntityManagerFactory factory = ordersEntityManagerFactory().getObject();
return new JpaTransactionManager(factory);
}
@Bean
public LocalContainerEntityManagerFactoryBean ordersEntityManagerFactory() {
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setDataSource(ordersDataSource());
factory.setPackagesToScan(new String[] {
"net.guides.springboot.springbootmultipledatasources.orders.entities"
});
factory.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
Properties jpaProperties = new Properties();
jpaProperties.put("hibernate.hbm2ddl.auto", env.getProperty("spring.jpa.hibernate.ddl-auto"));
jpaProperties.put("hibernate.show-sql", env.getProperty("spring.jpa.show-sql"));
factory.setJpaProperties(jpaProperties);
return factory;
}
@Bean
public DataSourceInitializer ordersDataSourceInitializer() {
DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
dataSourceInitializer.setDataSource(ordersDataSource());
ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
databasePopulator.addScript(new ClassPathResource("orders-data.sql"));
dataSourceInitializer.setDatabasePopulator(databasePopulator);
dataSourceInitializer.setEnabled(env.getProperty("datasource.orders.initialize", Boolean.class, false));
return dataSourceInitializer;
}
}
package net.guides.springboot.springbootmultipledatasources.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import net.guides.springboot.springbootmultipledatasources.orders.entities.Order;
import net.guides.springboot.springbootmultipledatasources.orders.repositories.OrderRepository;
import net.guides.springboot.springbootmultipledatasources.security.entities.User;
import net.guides.springboot.springbootmultipledatasources.security.repositories.UserRepository;
/**
* @author Ramesh Fadatare
*
*/
@Service
public class UserOrdersService
{
@Autowired
private OrderRepository orderRepository;
@Autowired
private UserRepository userRepository;
@Transactional(transactionManager="securityTransactionManager")
public List<User> getUsers()
{
return userRepository.findAll();
}
@Transactional(transactionManager="ordersTransactionManager")
public List<Order> getOrders()
{
return orderRepository.findAll();
}
}
packagenet.guides.springboot.springbootmultipledatasources.controllers;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.stereotype.Controller;
importorg.springframework.ui.Model;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestMethod;
importnet.guides.springboot.springbootmultipledatasources.services.UserOrdersService;
/*** @author Ramesh Fadatare**/@ControllerpublicclassHomeController{
@AutowiredprivateUserOrdersServiceuserOrdersService;
@RequestMapping(value={"/", "/app/users"}, method=RequestMethod.GET)
publicStringgetUsers(Modelmodel)
{
model.addAttribute("users", userOrdersService.getUsers());
model.addAttribute("orders", userOrdersService.getOrders());
return"users";
}
}
让我们来看看如何使用OpenEntityManagerInViewFilter
在渲染视图时启用JPA实体LAZY关联集合的懒惰加载,你需要注册OpenEntityManagerInViewFilter
豆。
/**
*
*/
package net.guides.springboot.springbootmultipledatasources.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* @author Ramesh Fadatare
*
*/
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter
{
@Bean
public OpenEntityManagerInViewFilter securityOpenEntityManagerInViewFilter()
{
OpenEntityManagerInViewFilter osivFilter = new OpenEntityManagerInViewFilter();
osivFilter.setEntityManagerFactoryBeanName("securityEntityManagerFactory");
return osivFilter;
}
@Bean
public OpenEntityManagerInViewFilter ordersOpenEntityManagerInViewFilter()
{
OpenEntityManagerInViewFilter osivFilter = new OpenEntityManagerInViewFilter();
osivFilter.setEntityManagerFactoryBeanName("ordersEntityManagerFactory");
return osivFilter;
}
}
由于我们正在建立一个Web应用程序,所以该方法返回 users.html 视图。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>SpringBoot</title>
</head>
<body>
<div style="width: 20%; float:left">
<h1>Users</h1>
<hr/>
<div th:each="user : ${users}">
<h2>Name: <span th:text="${user.name}">Name</span></h2>
<h4>Addresses</h4>
<div th:each="addr : ${user.addresses}">
<p th:text="${addr.city}">City</p>
</div>
</div>
</div>
<div style="width: 80%; float:right">
<h1>Orders</h1>
<hr/>
<div th:each="order : ${orders}">
<h2>Customer Name: <span th:text="${order.customerName}">customerName</span></h2>
<h4>Order Items</h4>
<div th:each="item : ${order.orderItems}">
<p th:text="${item.productCode}">productCode</p>
</div>
</div>
</div>
</body>
</html>
SpringbootMultipleDatasourcesApplication.java
是一个入口点,所以在你的IDE中右击并选择运行,将在8080端口启动嵌入式tomcat服务器。
在浏览器中点击http://localhost:8080/链接将在浏览器中显示以下网页。
就这样,我完成了一个带有多个数据源的Spring Boot Web应用程序的开发。
在我的GitHub仓库下载这个例子的源代码:https://github.com/RameshMF/springboot-jpa-multiple-datasources
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.javaguides.net/2018/09/spring-boot-jpa-multiple-data-sources-example.html
内容来源于网络,如有侵权,请联系作者删除!