首页 > 其他分享 >Spring Boot 整合 Jpa 多数据源

Spring Boot 整合 Jpa 多数据源

时间:2022-10-09 20:38:26浏览次数:48  
标签:Jpa 数据源 spring jpa datasource Spring org properties


工程创建

首先是创建一个 Spring Boot 工程,创建时添加基本的 Web、Jpa 以及 MySQL 依赖,如下

Spring Boot 整合 Jpa 多数据源_mysql

 pom依赖

<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>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.28</version>
<scope>runtime</scope>
</dependency>

application.properties

#  数据源一
spring.datasource.one.username=root
spring.datasource.one.password=root
spring.datasource.one.url=jdbc:mysql:///test01?useUnicode=true&characterEncoding=UTF-8
spring.datasource.one.type=com.alibaba.druid.pool.DruidDataSource

# 数据源二
spring.datasource.two.username=root
spring.datasource.two.password=root
spring.datasource.two.url=jdbc:mysql:///test02?useUnicode=true&characterEncoding=UTF-8
spring.datasource.two.type=com.alibaba.druid.pool.DruidDataSource

# Jpa配置
spring.jpa.properties.database=mysql
spring.jpa.properties.show-sql=true
spring.jpa.properties.database-platform=mysql
spring.jpa.properties.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL57Dialect

配置两个 DataSource

@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource.one")
@Primary
DataSource dsOne() {
return DruidDataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties(prefix = "spring.datasource.two")
DataSource dsTwo() {
return DruidDataSourceBuilder.create().build();
}
}

这里的配置和前文的多数据源配置基本一致,但是注意多了一个在 Spring 中使用较少的注解 @Primary,这个注解一定不能少,否则在项目启动时会出错,@Primary 表示当某一个类存在多个实例时,优先使用哪个实例。

Jpa配置

我们将jpa两个数据源的配置分成两个类,第一个如下

@Configuration
@EnableJpaRepositories(basePackages = "org.javayihao.jpa.dao",entityManagerFactoryRef = "localContainerEntityManagerFactoryBeanOne",transactionManagerRef = "platformTransactionManagerOne")
public class JpaConfigOne {
@Autowired
@Qualifier(value = "dsOne")
DataSource dsOne;
@Autowired
JpaProperties jpaProperties;
@Bean
@Primary
LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBeanOne(EntityManagerFactoryBuilder builder) {
return builder.dataSource(dsOne)
.packages("org.javayihao.jpa.model")
.properties(jpaProperties.getProperties())
.persistenceUnit("pu1")
.build();
}
@Bean
PlatformTransactionManager platformTransactionManagerOne(EntityManagerFactoryBuilder builder) {
LocalContainerEntityManagerFactoryBean factoryBeanOne = localContainerEntityManagerFactoryBeanOne(builder);
return new JpaTransactionManager(factoryBeanOne.getObject());
}
}

首先这里注入 dsOne,再注入 JpaProperties,JpaProperties 是系统提供的一个实例,里边的数据就是我们在 application.properties 中配置的 jpa 相关的配置。然后我们提供两个 Bean,分别是 LocalContainerEntityManagerFactoryBean 和 PlatformTransactionManager 事务管理器,不同于 MyBatis 和 JdbcTemplate,在 Jpa 中,事务一定要配置。在提供 LocalContainerEntityManagerFactoryBean 的时候,需要指定 packages,这里的 packages 指定的包就是这个数据源对应的实体类所在的位置,另外在这里配置类上通过 @EnableJpaRepositories 注解指定 dao 所在的位置,以及 LocalContainerEntityManagerFactoryBean 和 PlatformTransactionManager 分别对应的引用的名字。

好了,这样第一个就配置好了,第二个基本和这个类似,主要有几个不同点:

    dao 的位置不同
    persistenceUnit 不同
    相关 bean 的名称不同

注意实体类可以共用。

@Configuration
@EnableJpaRepositories(basePackages = "org.javayihao.jpa.dao2",entityManagerFactoryRef = "localContainerEntityManagerFactoryBeanTwo",transactionManagerRef = "platformTransactionManagerTwo")
public class JpaConfigTwo {
@Autowired
@Qualifier(value = "dsTwo")
DataSource dsTwo;
@Autowired
JpaProperties jpaProperties;
@Bean
LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBeanTwo(EntityManagerFactoryBuilder builder) {
return builder.dataSource(dsTwo)
.packages("org.javayihao.jpa.model")
.properties(jpaProperties.getProperties())
.persistenceUnit("pu2")
.build();
}
@Bean
PlatformTransactionManager platformTransactionManagerTwo(EntityManagerFactoryBuilder builder) {
LocalContainerEntityManagerFactoryBean factoryBeanTwo = localContainerEntityManagerFactoryBeanTwo(builder);
return new JpaTransactionManager(factoryBeanTwo.getObject());
}
}

dao接口

数据源一的

package org.javayihao.jpa.dao;
public interface UserDao extends JpaRepository<User,Integer> {
List<User> getUserByAddressEqualsAndIdLessThanEqual(String address, Integer id);
@Query(value = "select * from t_user where id=(select max(id) from t_user)",nativeQuery = true)
User maxIdUser();
}

数据源二的

package org.javayihao.jpa.dao2;
public interface UserDao2 extends JpaRepository<User,Integer> {
List<User> getUserByAddressEqualsAndIdLessThanEqual(String address, Integer id);

@Query(value = "select * from t_user where id=(select max(id) from t_user)",nativeQuery = true)
User maxIdUser();
}

公共的实体类

package org.javayihao.jpa.model;
@Entity(name = "t_user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String username;
private String address;
//省略getter/setter
}

到此,所有的配置就算完成了,接下来就可以在 Service 中注入不同的 UserDao,不同的 UserDao 操作不同的数据源。

Spring Boot 整合 Jpa 多数据源_mysql_02

标签:Jpa,数据源,spring,jpa,datasource,Spring,org,properties
From: https://blog.51cto.com/u_11334685/5741377

相关文章

  • Spring Boot 整合多数据源
    一、jdbcTemplate多数据源1、依赖引入<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency>......
  • Spring Boot整合 MyBatis 多数据源
    工程创建首先需要创建MyBatis项目,项目创建和前文的一样,添加MyBatis、MySQL以及Web依赖:pom文件<dependency><groupId>org.springframework.boot</groupId><ar......
  • Springboot中tomcat配置、三大组件配置、拦截器配置
    1.tomcat配置Springboot默认使用的就是嵌入式servlet容器即tomcat,对于web项目,如果使用的是外部tomcat,相关配置比如访问端口、资源路径等可以在tomcat的conf文件下配置。但是......
  • Springboot整合JPA
      概述前面文章记录了Springboot整合Mybatis以及Spingboot整合JDBCTemlate的过程,这篇文章记录Springboot整合JPA操作过程。jpa实际也是用来操作数据库的持久层框架,如何使......
  • Springboot异常处理和自定义错误页面及@ControllerAdvice 注解的三种使用场景!五、@Con
    一、前言springboot默认发生4xx错误时候,pc端响应的页面如下如果是移动端(手机端)将会响应json格式的数据,如下二、Springboot异常处理为什么我们请求错误的路径,boot会给我们返......
  • Springboot整合jsp
    1.创建项目2.选择war工程3.这里可以选择web模块引入(我这里选择的boot版本是2.2.1)4.必须要引入的依赖<dependency><groupId>org.apache.tomcat.embed</groupId><artifa......
  • Springboot整合freemarker
    一、概述FreeMarker是一款模板引擎:即一种基于模板和要改变的数据,并用来生成输出文本(HTML网页,电子邮件,配置文件,源代码等)的通用工具。它不是面向最终用户的,而是一个Jav......
  • springboot高级——消息队列相关
    写在前边:本文学习尚硅谷的springboot高级整理笔记。消息队列是什么,有什么好处?通过异步处理提高系统性能和削峰、降低系统耦合性。目前使用较多的消息队ActiveMQ,RabbitMQ,Kafk......
  • 《Spring Cloud微服务实战》翟永超(著)
     /*免责声明:全部内容都属于是段友分享,我只是属于整理。**/   /*  写在前边,个人觉得****弄一个积分下载,就是在自掘坟墓。表面上看起来是可以为个人赚积分,实际砍掉分享......
  • springMVC的工作流程
    一.springMVC的常用组件1)DispatcherServlet是一种前端控制器,由框架提供。作用:统一处理请求和响应。除此之外还是整个流程控制的中心,由DispatcherServlet来调用其他组......