一、JPA配置多数据源
上一节讲解了jdbcTemplate配置多数据源,但其实实际中使用jdbcTemplate的情况还是比较少的,这一节我们来看看JPA的数据源怎么配置。
该章节是在JPA的使用基础上讲解的,并不会过多讲解JPA的使用,如果不熟悉JPA的使用的话,可以看看之前的JPA讲解:Spring Boot集成Spring Data JPA。
首先是依赖,除了JPA及数据库的相关依赖外,多数据源并不会增加额外依赖。
<!--mysql连接-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--druid连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<!--jpa依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa
</artifactId>
</dependency>
在配置文件中,声明使用jpa,并指明数据库方言,这里使用的是mysql,然后数据源部分,配置master及slave两个数据库,此处根据实际情况进行配置即可。
server:
port: 10900
spring:
datasource:
master:
# 新版驱动从com.mysql.jdbc.Driver变更为com.mysql.cj.jdbc.Driver
driver-class-name: com.mysql.cj.jdbc.Driver
# 数据源需要添加时间标准和指定编码格式解决乱码 You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
password: