Springboot 2.1.5 配置JPA多數據源

最近在學sprinJpa,照着網上博客想試着配一下Jpa的多數據源,但發現由於springboot版本過高的問題,網上的demo都不適用,致使找了好久才找到解決辦法。如今把操做過程記錄以下。mysql

1、yml配置

spring:
  datasource:
    test1:
      driver-class-name: com.mysql.jdbc.Driver
      password: 123456
      #url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
      #springboot2.0以上
      jdbc-url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
      username: root
    test2:
      driver-class-name: com.mysql.jdbc.Driver
      password: 123456
      #url: jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
      #springboot2.0以上
      jdbc-url: jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
      username: root
  jpa:
    ## 是否打印sql
    show-sql: true
    properties:
      hibernate:
        # 指定引擎爲Innodb
        dialect: org.hibernate.dialect.MySQL5InnoDBDialect
        hbm2ddl:
          # create: 每次加載 hibernate 時都會刪除上一次的生成的表,
          # 而後根據你的 model 類再從新來生成新表,哪怕兩次沒有任何改變也要這樣執行,
          # 這就是致使數據庫表數據丟失的一個重要緣由。
          # create-drop :每次加載 hibernate 時根據 model 類生成表,可是 sessionFactory 一關閉,表就自動刪除。
          # update:最經常使用的屬性,第一次加載 hibernate 時根據 model 類會自動創建起表的結構(前提是先創建好數據庫),之後加載 hibernate 時根據 model 類自動更新表結構,即便表結構改變了但表中的行仍然存在不會刪除之前的行。要注意的是當部署到服務器後,表結構是不會被立刻創建起來的,是要等 應用第一次運行起來後纔會。
          # validate :每次加載 hibernate 時,驗證建立數據庫表結構,只會和數據庫中的表進行比較,不會建立新表,可是會插入新值。
          auto: update

2、註冊datasource到spring容器

@Configuration
public class DataSourceConfig {
    @Bean(name = "primaryDataSource")
    @Primary
    @Qualifier("primaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.test1")
    public DataSource primaryDataSource() {
        System.out.println("-------------------- primaryDataSource初始化 ---------------------");
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "secondaryDataSource")
    @Qualifier("secondaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.test2")
    public DataSource secondaryDataSource() {
        System.out.println("-------------------- secondaryDataSource初始化---------------------");
        return DataSourceBuilder.create().build();
    }
}

3、註冊jpa相關對象進入spring容器

數據源1:spring

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef="entityManagerFactoryPrimary",
        transactionManagerRef="transactionManagerPrimary",
        basePackages= { "com.czcstudy.springbootdemo.day1.dao.test1" }) //設置Repository所在位置
public class RepositoryPrimaryConfig {
    @Autowired
    @Qualifier("primaryDataSource")
    private DataSource primaryDataSource;
    @Autowired
    private JpaProperties jpaProperties;
    @Autowired
    private HibernateProperties hibernateProperties;

    @Primary
    @Bean(name = "entityManagerFactoryPrimary")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(
            EntityManagerFactoryBuilder builder) {
		//網上文章大多數都是jpaProperties.getHibernateProperties(dataSource);就直接獲得了hibernate的配置map,
		//但這個方法在springboot2.0+好像就捨棄了,因此這裏改爲這樣。
        Map<String, Object> properties = hibernateProperties.determineHibernateProperties(
                jpaProperties.getProperties(), new HibernateSettings());
        return builder.dataSource(primaryDataSource).properties(properties)
                .packages("com.czcstudy.springbootdemo.day1.bean.po").build();//實體包路徑
    }

    @Primary
    @Bean(name = "transactionManagerPrimary")
    public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
    }

數據源2:sql

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef="entityManagerFactorySecondary",
        transactionManagerRef="transactionManagerSecondary",
        basePackages= { "com.czcstudy.springbootdemo.day1.dao.test2" }) //設置Repository所在位置
public class RepositorySecondaryConfig {
    @Autowired
    @Qualifier("secondaryDataSource")
    private DataSource secondaryDataSource;
    @Autowired
    private JpaProperties jpaProperties;
    @Autowired
    private HibernateProperties hibernateProperties;

    @Bean(name = "entityManagerFactorySecondary")
    public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary(
            EntityManagerFactoryBuilder builder) {
		//網上文章大多數都是jpaProperties.getHibernateProperties(dataSource);就直接獲得了hibernate的配置map,
		//但這個方法在springboot2.0+好像就捨棄了,因此這裏改爲這樣。
        Map<String, Object> properties = hibernateProperties.determineHibernateProperties(
                jpaProperties.getProperties(), new HibernateSettings());
        return builder.dataSource(secondaryDataSource).properties(properties)
                .packages("com.czcstudy.springbootdemo.day1.bean.po").build();//實體的包路徑
    }

    @Bean(name = "transactionManagerSecondary")
    public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactorySecondary(builder).getObject());
    }
}

4、使用spring事務例

@Service
public class JpaTestServiceImpl implements JpaTestService {
    @Autowired
    private UserJpaTest2Dao userRepository2;

    @Override
    @Transactional(value = "transactionManagerSecondary",rollbackFor = RuntimeException.class)
    public void test(){
        List<UserJpaTest> userJpaTestList  = userRepository2.findAll();
        System.out.println(userJpaTestList);
    }
}

其中指定的value就是前面註冊的PlatformTransactionManager對象名稱,多數據源時須要指定。數據庫

5、小結

以上就是springboot2.1.5 配置jpa多數據源的方法,啓動項目咱們能夠看到springboot

HikariPool鏈接池已經啓動了,這是springboot的默認數據庫鏈接池,因此鏈接池咱們這裏就不本身配了。服務器

相關文章
相關標籤/搜索