SpringBoot+JPA配置双数据源

干货干货,直接上源代码

(一)yml数据库配置

 

spring:
  aop:
    auto: true
    proxy-target-class: true
  datasource:
    primary:
      url: jdbc:mysql://*********:3306/******?characterEncoding=utf-8&useSSL=true&autoReconnect=true
      username: ****
      password: ******
    secondary:
      url: jdbc:mysql://*********:3306/******?characterEncoding=utf-8&useSSL=true&autoReconnect=true
      username: ****
      password: ******
    tomcat:
      validation-query: select 1
    type: com.alibaba.druid.pool.DruidDataSource
    validationQuery: select 1

(二)配置文件的编写

PrimaryConfig

 

import com.alibaba.druid.pool.DruidDataSource;
import org.hibernate.cfg.Environment;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy;
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.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;

import javax.persistence.ValidationMode;
import javax.sql.DataSource;
import java.util.HashMap;

/**
 * @author 
 */
@Configuration
@EnableJpaRepositories(
        basePackages = "com.******.repository.******", //配置dao层包路径
        entityManagerFactoryRef = "primaryEntityManager",
        transactionManagerRef = "primaryTransactionManager"
)
public class PrimaryConfig {
    @Value("${spring.datasource.primary.url}")
    private String url;
    @Value("${spring.datasource.primary.password}")
    private String password;
    @Value("${spring.datasource.primary.username}")
    private String username;

    @Bean
    @Primary
    public LocalContainerEntityManagerFactoryBean primaryEntityManager() {
        LocalContainerEntityManagerFactoryBean em
                = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(primaryDataSource());
        em.setPackagesToScan("com.******.dataobject.******");   //配置对应的实体类路径
        em.setValidationMode(ValidationMode.AUTO);
        HibernateJpaVendorAdapter vendorAdapter
                = new HibernateJpaVendorAdapter();
        vendorAdapter.setShowSql(true);
        vendorAdapter.setDatabase(Database.MYSQL);
        vendorAdapter.setGenerateDdl(true);
        vendorAdapter.setPrepareConnection(true);
        em.setJpaVendorAdapter(vendorAdapter);
        HashMap properties = new HashMap<>(2);
        properties.put(Environment.PHYSICAL_NAMING_STRATEGY, new SpringPhysicalNamingStrategy());
        properties.put(Environment.AUTOCOMMIT, true);
//        properties.put("hibernate.naming.physical-strategy", "org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy");
//        properties.put("hibernate.naming.implicit-strategy", "org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy");
        em.setJpaPropertyMap(properties);
        return em;
    }

    @Primary
    @Bean
    public DataSource primaryDataSource() {
//        DriverManagerDataSource dataSource
//                = new DriverManagerDataSource();
        DruidDataSource dataSource = new DruidDataSource();
//        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setValidationQuery("select 1");
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean
    @Primary
    public PlatformTransactionManager primaryTransactionManager() {
        JpaTransactionManager transactionManager
                = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(
                primaryEntityManager().getObject());
        return transactionManager;
    }
}

SecondaryConfig

 

import com.alibaba.druid.pool.DruidDataSource;
import org.hibernate.cfg.Environment;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy;
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.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;

/**
 * @author 
 */
@Configuration
@EnableJpaRepositories(
        basePackages = "com.******.repository.******",
        entityManagerFactoryRef = "secondaryEntityManager",
        transactionManagerRef = "secondaryTransactionManager"
)
public class SecondaryConfig {
    @Value("${spring.datasource.secondary.url}")
    private String url;
    @Value("${spring.datasource.secondary.password}")
    private String password;
    @Value("${spring.datasource.secondary.username}")
    private String username;

    @Bean
    public LocalContainerEntityManagerFactoryBean secondaryEntityManager() {
        LocalContainerEntityManagerFactoryBean em
                = new LocalContainerEntityManagerFactoryBean();
        em.setPackagesToScan("com.******.dataobject.******");
        em.setDataSource(secondaryDataSource());
        HibernateJpaVendorAdapter vendorAdapter
                = new HibernateJpaVendorAdapter();
        vendorAdapter.setShowSql(true);
        vendorAdapter.setDatabase(Database.MYSQL);
        vendorAdapter.setGenerateDdl(true);
        em.setJpaVendorAdapter(vendorAdapter);
        HashMap properties = new HashMap<>(2);
        properties.put(Environment.PHYSICAL_NAMING_STRATEGY, new SpringPhysicalNamingStrategy());
        properties.put(Environment.AUTOCOMMIT, true);

//        properties.put("hibernate.naming.physical-strategy", "org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy");
//        properties.put("hibernate.naming.implicit-strategy", "org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy");
        em.setJpaPropertyMap(properties);
        return em;
    }

    @Bean
    public DataSource secondaryDataSource() {
//        DriverManagerDataSource dataSource
//                = new DriverManagerDataSource();
//        BasicDataSource dataSource = new BasicDataSource();
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setValidationQuery("select 1");
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl(url);
        dataSource.setPassword(password);
        dataSource.setUsername(username);
        return dataSource;
    }

    @Bean
    public PlatformTransactionManager secondaryTransactionManager() {
        JpaTransactionManager transactionManager
                = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(
                secondaryEntityManager().getObject());
        return transactionManager;
    }

}

 

OK,结束!

 

你可能感兴趣的:(java,mysql)