SpringBoot整合JPA多数据源

一、创建项目并导入依赖

   

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-jpa</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>

<scope>runtime</scope>

<version>5.1.27</version>

</dependency>

   

   

二、相关配置

   

Application.proteries

   

spring.datasource.one.type=com.alibaba.druid.pool.DruidDataSource

spring.datasource.one.username=root

spring.datasource.one.password=123

spring.datasource.one.url=jdbc:mysql://127.0.0.1:3306/jpa?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=GMT

   

spring.datasource.two.type=com.alibaba.druid.pool.DruidDataSource

spring.datasource.two.username=root

spring.datasource.two.password=123

spring.datasource.two.url=jdbc:mysql://127.0.0.1:3306/jpa2?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=GMT

   

spring.jpa.properties.show-sql=true

spring.jpa.properties.database=mysql

spring.jpa.properties.database-platform=mysql

spring.jpa.properties.hibernate.ddl-auto=update

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL57Dialect

   

   

   

DataSourceConfig.class

   

   

注:必须指定一个@Primary

   

JpaConfigOne.class

   

   

   

@Primary

表示当某一个类存在多个实例时,优先使用哪个实例。

  

Properties()

JpaProperties是系统提供的一个实例,里边的数据就是我们在application.properties中配置的jpa相关的配置

packages()

这里的packages指定的包就是这个数据源对应的实体类所在的位置

persistenceUnit()

相当于为这个配置取一个别名

   

   

JpaConfigTwo.class

   

   

注:这个没有@primary

   

   

   

Pojo层

   

   

   

Dao1和Dao2层

   

   

   

   

Controller层

   

   

   

猜你喜欢

转载自www.cnblogs.com/fernfei/p/12119601.html