在实际项目中往往会使用2个数据源,这个时候就需要做额外的配置了。下面的配置在2.0.1.RELEASE 测试通过

1、配置文件

  配置两个数据源

spring.datasource.url=jdbc:mysql://localhost:13306/first?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.seconddatasource.url=jdbc:mysql://localhost:3306/second?useUnicode\=true&characterEncoding=utf-8&useSSL=false
spring.seconddatasource.driverClassName=com.mysql.jdbc.Driver
spring.seconddatasource.username=root
spring.seconddatasource.password=

  

2、entity

  创建两个简单的entity,它们分别对应不同的数据库。

  先看第一个entity,user

package com.example.first.entity;

@Entity
public class User { @Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String email;
private int age;
}

  第二个entity, product

package com.example.second.entity;

@Entity
public class Product { @Id
private Long id;
private String name;
private double price;
}

  注意:这两个enty位于不同的包里面。

3、Repository

  创建两个对应的Repository,注意他们也位于不同的包里

  

package com.example.first.dao;

public interface UserRepository
extends JpaRepository<User, Long> { }

  

package com.example.second.dao;

public interface ProductRepository
extends JpaRepository<Product, Long> { }

  

4、java 配置

  有两个数据源,需要两个配置文件,分别配置下面这几个Bean

  DataSource

  EntityManagerFactory

  TransactionManager

  首先配置第一个数据源,我把它作为主数据源,注意,它们都使用了@Prime注解

@Configuration
@EnableJpaRepositories(basePackages = "com.example.first.dao",
entityManagerFactoryRef = "firstEntityManager",
transactionManagerRef = "firstTransactionManager")
public class FirstDataSourceConfig { @Bean
@Primary
public LocalContainerEntityManagerFactoryBean firstEntityManager(EntityManagerFactoryBuilder builder) { Map<String, String> properties = new HashMap<>();
properties.put("hibernate.implicit_naming_strategy",
"org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy");
properties.put("hibernate.physical_naming_strategy",
"org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy");
return builder
.dataSource(firstDataSource())
.packages("com.example.user.entity")
.persistenceUnit("first")
.properties(properties)
.build();
} @Bean
@Primary
@ConfigurationProperties("spring.datasource")
public DataSourceProperties firstDataSourceProperties() {
return new DataSourceProperties();
} @Bean
@Primary
@ConfigurationProperties("spring.datasource")
public DataSource firstDataSource() {
return primaryDataSourceProperties().initializeDataSourceBuilder().build();
} @Primary
@Bean(name = "firstTransactionManager")
public PlatformTransactionManager firstTransactionManager(@Qualifier("firstEntityManager")
EntityManagerFactory firstEntityManagerFactory) {
return new JpaTransactionManager(firstEntityManagerFactory);
}
}

  

  接下来配置第二个数据源,和第一个完全一致,除了没有@Prime注解

@Configuration
@EnableJpaRepositories(
basePackages = "com.example.second.dao",
entityManagerFactoryRef = "secondEntityManager",
transactionManagerRef = "secondTransactionManager"
)
public class SecondDataSourceConfig { @Bean
public LocalContainerEntityManagerFactoryBean secondEntityManager(EntityManagerFactoryBuilder builder) {
Map<String, String> properties = new HashMap<>();
properties.put("hibernate.implicit_naming_strategy",
"org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy");
properties.put("hibernate.physical_naming_strategy",
"org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy");
return builder
.dataSource(secondDataSource())
.packages("com.example.second.entity")
.persistenceUnit("second")
.properties(properties)
.build();
} @Bean
@ConfigurationProperties("spring.seconddatasource")
public DataSourceProperties secondDataSourceProperties() {
return new DataSourceProperties();
} @Bean
@ConfigurationProperties("spring.seconddatasource")
public DataSource secondDataSource() {
return secondDataSourceProperties().initializeDataSourceBuilder().build();
} @Bean(name = "secondTransactionManager")
public PlatformTransactionManager secondTransactionManager(@Qualifier("secondEntityManager")
EntityManagerFactory secondEntityManagerFactory) {
return new JpaTransactionManager(secondEntityManagerFactory);
}
}

  

5、使用

  和单数据源的jpa使用方式基本一致。当使用事务注解是,第一个数据源的注解可以直接使用@Transactional,第二个为了区分必须使用@Transactional(value="secondTransactionManager")。可以在一个事务中调用另外一个数据源的事务。

2.0.1.RELEASE

spring boot jpa 多数据源配置的更多相关文章

  1. 工具篇-Spring boot JPA多数据源

    写这篇博文是因为这个东西坑太多,首先说明下边实现的多数据源不是动态切换的,应该算是静态的. 坑一.pom文件 pom中spring boot以及mysql connector的版本一定要注意. < ...

  2. spring boot mybatis 多数据源配置

    package com.xynet.statistics.config.dataresources; import org.springframework.jdbc.datasource.lookup ...

  3. spring boot Mybatis多数据源配置

    关于 有时候,随着业务的发展,项目关联的数据来源会变得越来越复杂,使用的数据库会比较分散,这个时候就会采用多数据源的方式来获取数据.另外,多数据源也有其他好处,例如分布式数据库的读写分离,集成多种数据 ...

  4. Spring Boot + Mybatis 多数据源配置实现读写分离

    本文来自网易云社区 作者:王超 应用场景:项目中有一些报表统计与查询功能,对数据实时性要求不高,因此考虑对报表的统计与查询去操作slave db,减少对master的压力. 根据网上多份资料测试发现总 ...

  5. Springboot spring data jpa 多数据源的配置01

    Springboot spring data jpa 多数据源的配置 (说明:这只是引入了多个数据源,他们各自管理各自的事务,并没有实现统一的事务控制) 例: user数据库   global 数据库 ...

  6. Spring Boot(五):Spring Boot Jpa 的使用

    在上篇文章Spring Boot(二):Web 综合开发中简单介绍了一下 Spring Boot Jpa 的基础性使用,这篇文章将更加全面的介绍 Spring Boot Jpa 常见用法以及注意事项. ...

  7. Spring Boot Jpa 的使用

    Spring Boot Jpa 介绍 首先了解 Jpa 是什么? Jpa (Java Persistence API) 是 Sun 官方提出的 Java 持久化规范.它为 Java 开发人员提供了一种 ...

  8. (转)Spring Boot(五):Spring Boot Jpa 的使用

    http://www.ityouknow.com/springboot/2016/08/20/spring-boot-jpa.html 在上篇文章Spring Boot(二):Web 综合开发中简单介 ...

  9. Spring Boot2.x 动态数据源配置

    原文链接: Spring Boot2.x 动态数据源配置 基于 Spring Boot 2.x.Spring Data JPA.druid.mysql 的动态数据源配置Demo,适合用于数据库的读写分 ...

随机推荐

  1. BZOJ 2337 XOR和路径 | 高斯消元 期望 位运算

    BZOJ 2337 XOR和路径 题解 这道题和游走那道题很像,但又不是完全相同. 因为异或,所以我们考虑拆位,分别考虑每一位: 设x[u]是从点u出发.到达点n时这一位异或和是1的概率. 对于所有这 ...

  2. Longest Word in Dictionary through Deleting - LeetCode

    目录 题目链接 注意点 解法 小结 题目链接 Longest Word in Dictionary through Deleting - LeetCode 注意点 长度一样的字符串要按字典序返回较小的 ...

  3. MySQL基本了解与使用

    MySQL的相关概念介绍 MySQL 为关系型数据库(Relational Database Management System), 这种所谓的"关系型"可以理解为"表格 ...

  4. .gitignore 无效问题

    利用.gitignore过滤文件,如编译过程中的中间文件,等等,这些文件不需要被追踪管理. 现象: 在.gitignore添加file1文件,以过滤该文件,但是通过Git status查看仍显示fil ...

  5. Swarm配置文件管理

    一.前言 Docker 17.06引入了swarm服务配置,允许您在服务映像外部或运行容器中存储非敏感信息,例如配置文件. 这允许您保持镜像尽可能通用,而无需将配置文件绑定到容器或使用环境变量.在Sw ...

  6. org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session异常解决办法

    org.hibernate.NonUniqueObjectException: a different object with the same identifier value was alread ...

  7. 关于构造IOCTL命令的学习心得

    在编写ioctl代码之前,需要选择对应不同命令的编号.为了防止对错误的设备使用正确的命令,命令号应该在系统范围内唯一,这种错误匹配并不是不会发生,程序可能发现自己正在试图对FIFO和audio等这类非 ...

  8. LazyMay:实现同步和异步任务的顺序执行

    在掘金看到的文章,流程控制同步和异步任务的顺序执行,收益匪浅,工作中能用到. 1.实现以下效果 实现一个LazyMan,可以按照以下方式调用: LazyMan(“Hank”)输出: Hi! This ...

  9. seaborn基础整理

    seaborn是基于matplotlib的更高级的做图工具,下面主要针对以下几个部分进行整理: 第一部分:https://douzujun.github.io/page/%E6%95%B0%E6%8D ...

  10. 服务器能ping通ip,通不了域名解决方案

    # 将网卡配置文件配置固定ip后,添加DNS解析,然后重启网卡即可: [root@a ~]# tail -2 /etc/sysconfig/network-scripts/ifcfg-ens160 D ...