springboot+jpa配置多数据源(Oracle+SqlServer)

  • Post author:
  • Post category:其他


本贴主要讲解配置多数据源

springboot+jpa的整合需要自行准备好

1.maven中要导入Oracle和SqlServer的jar包

        <dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jdbc</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<!--oracle驱动 -->
		<dependency>
			<groupId>com.oracle</groupId>
			<artifactId>ojdbc6</artifactId>
			<version>11.2.0.3</version>
			<scope>system</scope>
			<systemPath>${xxx}/src/main/webapp/WEB-INF/lib/ojdbc6-11.2.0.3.jar</systemPath>
		</dependency>
		<dependency>
			<groupId>com.oracle</groupId>
			<artifactId>ojdbc6</artifactId>
			<version>11.1.0.7.0</version>
			<scope>system</scope>
			<systemPath>${xxx}/src/main/webapp/WEB-INF/lib/ojdbc6.jar</systemPath>
		</dependency>
		<dependency>
			<groupId>com.oracle</groupId>
			<artifactId>ojdbc5</artifactId>
			<version>11.1.0.7.0</version>
			<scope>system</scope>
			<systemPath>${xxx}/src/main/webapp/WEB-INF/lib/ojdbc5.jar</systemPath>
		</dependency>

        <!--SQL server-->
		<dependency>
			<groupId>com.microsoft.sqlserver</groupId>
			<artifactId>sqljdbc4</artifactId>
			<version>4.0.0</version>
		</dependency>

2.在yml文件中配置双数据源等信息

spring:
  datasource:
    database1:
      # --------------- Oracle -----------------#
      driver-class-name: oracle.jdbc.OracleDriver
      url: jdbc:oracle:thin:@IP:端口:数据库
      username: xxxx
      password: xxxx
    database2:
      # --------------- SQL Server -----------------#
      driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
      url: jdbc:sqlserver://localhost:1433;DatabaseName=数据库
      username: xxxx
      password: xxxx

  #配置 Jpa
  jpa:
    database: mysql
    show-sql: true
    hibernate:
      ddl-auto: update
      naming:
        physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
    database-platform: org.hibernate.dialect.MySQL5Dialect

3.配置config文件

3.1 创建DataSourceConfig文件

import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

/**
 * 多数据源连接
 */
@Configuration
@Slf4j
public class DataSourceConfig {


    @Autowired
    private DataBase1Properties dataBase1Properties;

    @Autowired
    private DataBase2Properties dataBase2Properties;

    @Bean(name = "dataBase1DataSource")
    @Primary
    public DataSource dataBase1DataSource(){
        log.info("dataBase1DataSource初始化开始");
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl(dataBase1Properties.getUrl());
        dataSource.setUsername(dataBase1Properties.getUsername());
        dataSource.setPassword(dataBase1Properties.getPassword());
        dataSource.setDriverClassName(dataBase1Properties.getDriverClassName());
        log.info("dataBase1DataSource初始化成功");
        return dataSource;
    }

    @Bean(name = "dataBase2DataSource")
    public DataSource dataBase2DataSource(){
        log.info("dataBase2DataSource初始化开始");
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl(dataBase2Properties.getUrl());
        dataSource.setUsername(dataBase2Properties.getUsername());
        dataSource.setPassword(dataBase2Properties.getPassword());
        dataSource.setDriverClassName(dataBase2Properties.getDriverClassName());
        log.info("dataBase2DataSource初始化成功");
        return dataSource;
    }
}

3.2创建DataBase1Config


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryDataBase1", // 配置连接工厂
        transactionManagerRef = "transactionManagerDatabase1", // 配置事物管理器
        basePackages = {"com.dao.primary"} // 设置dao所在位置

)
public class DataBase1Config {

    // 配置数据源
    @Autowired
    private DataSource dataBase1DataSource;

    @Primary
    @Bean(name = "entityManagerFactoryDataBase1")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryDataBase1(EntityManagerFactoryBuilder builder) {
        return builder
                // 设置数据源
                .dataSource(dataBase1DataSource)
                //设置实体类所在位置.扫描所有带有 @Entity 注解的类
                .packages("com.domain.entity.primary")
                // Spring会将EntityManagerFactory注入到Repository之中.有了 EntityManagerFactory之后,
                // Repository就能用它来创建 EntityManager 了,然后 EntityManager 就可以针对数据库执行操作
                .persistenceUnit("database1PersistenceUnit")
                .build();

    }

    /**
     * 配置事物管理器
     *
     * @param builder
     * @return
     */
    @Bean(name = "transactionManagerDatabase1")
    PlatformTransactionManager transactionManagerDatabase1(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryDataBase1(builder).getObject());
    }
}

3.3创建DataBase2Config


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryDataBase2", // 配置连接工厂
        transactionManagerRef = "transactionManagerDatabase2", // 配置事物管理器
        basePackages = {"com.dao.secondary"} // 设置dao所在位置

)
public class DataBase2Config {

    // 配置数据源
    @Autowired
    @Qualifier("dataBase2DataSource")
    private DataSource dataBase2DataSource;

    @Bean(name = "entityManagerFactoryDataBase2")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryDataBase2(EntityManagerFactoryBuilder builder) {
        return builder
                // 设置数据源
                .dataSource(dataBase2DataSource)
                //设置实体类所在位置.扫描所有带有 @Entity 注解的类
                .packages("com.domain.entity.secondary")
                // Spring会将EntityManagerFactory注入到Repository之中.有了 EntityManagerFactory之后,
                // Repository就能用它来创建 EntityManager 了,然后 EntityManager 就可以针对数据库执行操作
                .persistenceUnit("database2PersistenceUnit")
                .build();

    }

    /**
     * 配置事物管理器
     *
     * @param builder
     * @return
     */
    @Bean(name = "transactionManagerDatabase2")
    PlatformTransactionManager transactionManagerDatabase2(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryDataBase2(builder).getObject());
    }
}

3.4创建DataBase1Properties

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@ConfigurationProperties(prefix = "spring.datasource.database1")
@Component
@Data
public class DataBase1Properties {
    private String url;

    private String username;

    private String password;

    private String driverClassName;
}

3.5创建DataBase2Properties

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@ConfigurationProperties(prefix = "spring.datasource.database2")
@Component
@Data
public class DataBase2Properties {
    private String url;

    private String username;

    private String password;

    private String driverClassName;
}

4.创建实体类(注意包名要跟DataBase1Config或DataBase2Config对应)

例如

package com.domain.entity.secondary;


import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;

@Data
@Entity
@Table(name="t_user")
public class TUser implements Serializable, Cloneable {

    @Id
    @Column(name = "id")
    private Integer id;

    @Column(name = "name")
    private String name;


}

5.创建DAO类(注意包名要跟DataBase1Config或DataBase2Config对应)

例如

package com.dao.secondary;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;

@Repository
public class TUserDAO extends JpaRepository<TUser, Integer>{

    @Query(value = "select * from aa where c_empoid = :empId", nativeQuery = true)
    List<Map<String, Object>> get(String empId);

}

重点需要注意的是要把两个数据源的代码做好区分,例如

数据源1的实体都放com.domain.entity.primary

数据源2的实体都放com.domain.entity.secondary

DAO层也是要做好区分



版权声明:本文为Amy_Victoria原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。