Springboot2.1.5配置JPA多數(shù)據(jù)源的方法

這篇文章主要介紹“Springboot 2.1.5 配置JPA多數(shù)據(jù)源的方法”,在日常操作中,相信很多人在Springboot 2.1.5 配置JPA多數(shù)據(jù)源的方法問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對(duì)大家解答”Springboot 2.1.5 配置JPA多數(shù)據(jù)源的方法”的疑惑有所幫助!接下來,請(qǐng)跟著小編一起來學(xué)習(xí)吧!

成都創(chuàng)新互聯(lián)公司專注于阿拉爾企業(yè)網(wǎng)站建設(shè),成都響應(yīng)式網(wǎng)站建設(shè)公司,商城建設(shè)。阿拉爾網(wǎng)站建設(shè)公司,為阿拉爾等地區(qū)提供建站服務(wù)。全流程按需制作網(wǎng)站,專業(yè)設(shè)計(jì),全程項(xiàng)目跟蹤,成都創(chuàng)新互聯(lián)公司專業(yè)和態(tài)度為您提供的服務(wù)

最近在學(xué)sprinJpa,照著網(wǎng)上博客想試著配一下Jpa的多數(shù)據(jù)源,但發(fā)現(xiàn)因?yàn)閟pringboot版本太高的問題,網(wǎng)上的demo都不適用,導(dǎo)致找了很久才找到解決辦法?,F(xiàn)在把操作過程記錄如下。

一、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 時(shí)都會(huì)刪除上一次的生成的表,
          # 然后根據(jù)你的 model 類再重新來生成新表,哪怕兩次沒有任何改變也要這樣執(zhí)行,
          # 這就是導(dǎo)致數(shù)據(jù)庫表數(shù)據(jù)丟失的一個(gè)重要原因。
          # create-drop :每次加載 hibernate 時(shí)根據(jù) model 類生成表,但是 sessionFactory 一關(guān)閉,表就自動(dòng)刪除。
          # update:最常用的屬性,第一次加載 hibernate 時(shí)根據(jù) model 類會(huì)自動(dòng)建立起表的結(jié)構(gòu)(前提是先建立好數(shù)據(jù)庫),以后加載 hibernate 時(shí)根據(jù) model 類自動(dòng)更新表結(jié)構(gòu),即使表結(jié)構(gòu)改變了但表中的行仍然存在不會(huì)刪除以前的行。要注意的是當(dāng)部署到服務(wù)器后,表結(jié)構(gòu)是不會(huì)被馬上建立起來的,是要等 應(yīng)用第一次運(yùn)行起來后才會(huì)。
          # validate :每次加載 hibernate 時(shí),驗(yàn)證創(chuàng)建數(shù)據(jù)庫表結(jié)構(gòu),只會(huì)和數(shù)據(jù)庫中的表進(jìn)行比較,不會(huì)創(chuàng)建新表,但是會(huì)插入新值。
          auto: update

二、注冊(cè)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();
    }
}

三、注冊(cè)jpa相關(guān)對(duì)象進(jìn)入spring容器

數(shù)據(jù)源1:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef="entityManagerFactoryPrimary",
        transactionManagerRef="transactionManagerPrimary",
        basePackages= { "com.czcstudy.springbootdemo.day1.dao.test1" }) //設(shè)置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) {
		//網(wǎng)上文章大多數(shù)都是jpaProperties.getHibernateProperties(dataSource);就直接得到了hibernate的配置map,
		//但這個(gè)方法在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();//實(shí)體包路徑
    }

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

數(shù)據(jù)源2:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef="entityManagerFactorySecondary",
        transactionManagerRef="transactionManagerSecondary",
        basePackages= { "com.czcstudy.springbootdemo.day1.dao.test2" }) //設(shè)置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) {
		//網(wǎng)上文章大多數(shù)都是jpaProperties.getHibernateProperties(dataSource);就直接得到了hibernate的配置map,
		//但這個(gè)方法在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();//實(shí)體的包路徑
    }

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

四、使用spring事務(wù)例

@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就是前面注冊(cè)的PlatformTransactionManager對(duì)象名稱,多數(shù)據(jù)源時(shí)需要指定。

五、小結(jié)

以上就是springboot2.1.5 配置jpa多數(shù)據(jù)源的方法,啟動(dòng)項(xiàng)目我們可以看到

Springboot 2.1.5 配置JPA多數(shù)據(jù)源的方法

HikariPool連接池已經(jīng)啟動(dòng)了,這是springboot的默認(rèn)數(shù)據(jù)庫連接池,所以連接池我們這里就不自己配了。

到此,關(guān)于“Springboot 2.1.5 配置JPA多數(shù)據(jù)源的方法”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!

文章題目:Springboot2.1.5配置JPA多數(shù)據(jù)源的方法
當(dāng)前網(wǎng)址:http://bm7419.com/article16/jdscgg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站制作、企業(yè)建站動(dòng)態(tài)網(wǎng)站、標(biāo)簽優(yōu)化、Google響應(yīng)式網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

小程序開發(fā)