Spring Boot JPA多数据源示例

x33g5p2x  于2022-10-06 转载在 Spring  
字(24.4k)|赞(0)|评价(0)|浏览(897)

在本文中,我们将学习如何在一个典型的Spring Boot Web应用程序中配置多个数据源并连接到多个数据库。我们将使用Spring Boot 2.0.5JPAHibernate 5ThymeleafH2数据库来构建一个简单的Spring Boot多数据源Web应用。
我们知道,如果你有一个单一的数据库,Spring Boot的自动配置是开箱即用的,并通过其属性提供大量的定制选项。但如果你的应用要求对应用配置有更多的控制,你可以关闭特定的自动配置,自己配置组件。

在这篇文章中,我们将逐步学习如何在同一个应用程序中使用多个数据库。如果我们需要连接多个数据库,我们需要配置各种Spring Bean,如DataSourcesTransactionManagersEntityManagerFactoryBeansDataSourceInitializers等,明确配置。

我们将建立什么?

我们将构建一个Spring Boot网络应用,其中security data被存储在一个数据库/模式中,order-related data被存储在另一个数据库/模式中。

让我们看看我们如何在Spring Boot中处理多个数据库,并使用基于Spring Data JPA的应用程序。

使用的工具和技术

  • Spring Boot - 2.0.5.RELEASE
  • JDK - 1.8或更高版本
  • Spring Framework - 5.0.9 RELEASE
  • Spring Data JPA - 2.0.10 RELEASE
  • Hibernate - 5.2.17.Final
  • Maven - 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.4
  • Group: net.guards.springboot
  • Artifact: springboot-multiple-datasources
  • Name: springboot-multiple-datasources
  • Description: 一个简单的用户管理应用的Rest API
  • Package Name : net.guards.springboot.springbootmultipledatasources
  • Packaging: jar (这是默认值)
  • Dependencies: Web, JPA, H2, DevTools
    一旦,所有的细节被输入,点击生成项目按钮将生成一个spring boot项目并下载。接下来,解压下载的压缩文件并将其导入你最喜欢的IDE。

项目结构

以下是项目结构 -

pom.xml文件

<?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上有JPAThymeleaf 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数据库配置

让我们来配置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

MySQL数据库配置

我们使用H2数据库来快速建立应用程序,但你也可以在application.properties文件中替换以下配置来使用MySQL数据库进行生产。

注意,我们使用了自定义属性键来配置两个数据源属性。
在下一步,我们将创建一个与安全相关的JPA实体和一个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;
    } 
}

Address.java

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;
    } 
}

Spring JPA存储库 - UserRepository.java

/**
* 
*/
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>
{
 
}

创建JPA实体--Order和OrderItem

/**
* 
*/
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;
    }
}

OrderItem.java

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;
    } 
}

Spring JPA Repository - OrderRepository.java

/**
* 
*/
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>{

}

初始化样本数据 - security-data.sql脚本

创建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);

初始化样本数据 - orders-data.sql脚本

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配置类。我们将通过连接SecurityDataSourceConfig.java中的安全数据库来配置Spring Bean,如DataSourceTransactionManagerEntityManagerFactoryBeanDataSourceInitializer

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支持。由于我们将有多个EntityManagerFactoryTransactionManager豆,我们通过指向各自的豆名来配置entityManagerFactoryReftransactionManagerRef的豆ID。我们还配置了basePackages属性,以指示在哪里寻找Spring Data JPA的仓库(包)。

创建安全数据源配置 - OrdersDataSourceConfig.java

创建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;
    }
}

创建UserOrdersService.java

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();
    }
}

创建HomeController.java

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

让我们来看看如何使用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 视图。

创建Thymeleaf页面 - 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

相关文章