springboot同時(shí)連接oracle和mysql數(shù)據(jù)庫

1捂龄、項(xiàng)目目錄結(jié)構(gòu)

image.png

2驴娃、pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.gysoft</groupId>
    <artifactId>emqdemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>emqdemo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.dmsoft.things</groupId>
            <artifactId>things-rbac</artifactId>
            <version>2.0.8-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Spring Data JPA 依賴 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <!-- 數(shù)據(jù)庫驅(qū)動(dòng)依賴 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>com.oracle.database.jdbc</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>11.2.0.4</version>
        </dependency>

        <!-- 數(shù)據(jù)庫連接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.18</version>
        </dependency>
        <!-- json工具-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.32</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

3署浩、DataSourceConfig

package com.dmsoft.wavetide.service.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import javax.sql.DataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

@Configuration
public class DataSourceConfig {

    @Bean
    @Primary
    @ConfigurationProperties("spring.datasource.location")
    DataSource dataSourceLocation() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.foreign")
    DataSource dataSourceForeign() {
        return DruidDataSourceBuilder.create().build();
    }

}

4、DataSource1Config

package com.dmsoft.wavetide.service.config;

import javax.annotation.Resource;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
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 java.util.HashMap;
import java.util.Map;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = {"com.dmsoft.wavetide.service.repository"},
        entityManagerFactoryRef = "entityManagerFactoryLocation",
        transactionManagerRef = "transactionManagerLocation")
public class DataSource1Config {
    @Resource(name = "dataSourceLocation")
    DataSource dataSourceLocation;
 
    @Autowired
    JpaProperties jpaProperties;

    @Primary
    @Bean
    LocalContainerEntityManagerFactoryBean entityManagerFactoryLocation(
            EntityManagerFactoryBuilder builder) {

        Map<String,String> map = new HashMap<>();
        map.put("hibernate.dialect","org.hibernate.dialect.Oracle12cDialect");// 設(shè)置對(duì)應(yīng)的數(shù)據(jù)庫方言
        jpaProperties.setProperties(map);

        return builder.dataSource(dataSourceLocation)
                .properties(jpaProperties.getProperties())
                .packages("com.dmsoft.wavetide.service.entity")
                .persistenceUnit("pu1")
                .build();
    }

//    private Map<String, String> getVendorProperties(DataSource dataSource) {
//        Map<String,String> map = new HashMap<>();
//        map.put("hibernate.dialect",localDialect);// 設(shè)置對(duì)應(yīng)的數(shù)據(jù)庫方言
//        jpaProperties.setProperties(map);
//        return jpaProperties.getHibernateProperties(dataSource);
//    }


    @Bean
    PlatformTransactionManager transactionManagerLocation(
            EntityManagerFactoryBuilder builder) {
        LocalContainerEntityManagerFactoryBean factoryOne
                = entityManagerFactoryLocation(builder);
        return new JpaTransactionManager(factoryOne.getObject());
    }
}

5掸哑、DataSource2Config

package com.dmsoft.wavetide.service.config;

import javax.annotation.Resource;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.support.AbstractBeanFactory;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
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 java.util.HashMap;
import java.util.Map;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "com.dmsoft.wavetide.service.feirepository",
        entityManagerFactoryRef = "entityManagerFactoryForeign",
        transactionManagerRef = "transactionManagerForeign")
public class DataSource2Config {
    @Resource(name = "dataSourceForeign")
    DataSource dataSourceForeign;
 
    @Autowired
    JpaProperties jpaProperties;
 
    @Bean
    LocalContainerEntityManagerFactoryBean entityManagerFactoryForeign(
            EntityManagerFactoryBuilder builder) {
        Map<String,String> map = new HashMap<>();
        map.put("hibernate.dialect","org.hibernate.dialect.MySQL5Dialect");
        jpaProperties.setProperties(map);
        return builder.dataSource(dataSourceForeign)
                .properties(jpaProperties.getProperties())
                .packages("com.dmsoft.wavetide.service.entity")
                .persistenceUnit("pu2")
                .build();
    }
 
    @Bean
    PlatformTransactionManager transactionManagerForeign(
            EntityManagerFactoryBuilder builder) {
        LocalContainerEntityManagerFactoryBean factoryTwo
                = entityManagerFactoryForeign(builder);
        return new JpaTransactionManager(factoryTwo.getObject());
    }
}

6 Controller

package com.dmsoft.wavetide.service.controller;

import com.dmsoft.wavetide.service.repository.impl.BookQueryDao2Impl;
import com.dmsoft.wavetide.service.entity.User;
import com.dmsoft.wavetide.service.entity.User1;
import com.dmsoft.wavetide.service.service.Book1Service;
import com.dmsoft.wavetide.service.feirepository.BookDao1;
import com.dmsoft.wavetide.service.repository.BookDao2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/api")
public class HelloController {

    @Autowired
    BookDao1 bookDao1;

    @Autowired
    BookDao2 bookDao2;

    @Autowired
    BookQueryDao2Impl bookQueryDao2;

    @Autowired
    Book1Service book1Service;

    @RequestMapping("/test")
    public void test(String asda1) {
        // 往第一個(gè)數(shù)據(jù)庫中插入數(shù)據(jù)
        User book1 = new User();
        book1.setPassword("asd");
        book1.setUsername("asda");
        bookDao1.save(book1); //使用save方法將數(shù)據(jù)保存到數(shù)據(jù)庫

        // 往第二個(gè)數(shù)據(jù)庫中插入數(shù)據(jù)
        User1 book2 = new User1();
        book2.setPassword("asd1");
        book2.setUsername(asda1);
        bookDao2.save(book2); //使用save方法將數(shù)據(jù)保存到數(shù)據(jù)庫
    }

    @GetMapping(value = "/findAll")
    public void findAll() {
        List<String> list = bookQueryDao2.findAll();
        System.out.println(list.size());

    }

    @GetMapping(value = "/findById")
    public void findById() {
        Integer id = 1;
        User1 list = bookDao2.findById(id).orElse(null);
        System.out.println(list.getUsername());

    }
}

7 entity

package com.dmsoft.wavetide.service.entity;

import javax.persistence.*;

import lombok.Data;

@Table(name = "q_user")
@Entity
@Data
public class User {

  @GeneratedValue(strategy= GenerationType.IDENTITY)
  @Id
  @Column(name = "id")
  private Integer id;

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

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

}


package com.dmsoft.wavetide.service.entity;

import lombok.Data;

import javax.persistence.*;

@Table(name = "q_user")
@Entity
@Data
public class User1 {
    @GeneratedValue(strategy= GenerationType.SEQUENCE)
    @Id
    @Column(name = "id")
    private Integer id;

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

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

8 BookDao1

package com.dmsoft.wavetide.service.feirepository;

import com.dmsoft.wavetide.service.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;

@Repository
public interface BookDao1 extends JpaRepository<User, Integer>, JpaSpecificationExecutor {
}

9 BookDao2

package com.dmsoft.wavetide.service.repository;

import com.dmsoft.wavetide.service.entity.User1;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface BookDao2 extends JpaRepository<User1, Integer>, JpaSpecificationExecutor {

    Optional<User1> findById(Integer id);
}

package com.dmsoft.wavetide.service.repository;

import java.util.List;


public interface BookQueryDao2 {

    List<String> findAll();
}

package com.dmsoft.wavetide.service.repository.impl;

import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;


@Transactional(value = "transactionManagerLocation")
@Repository
public class BookQueryDao2Impl{

    @Autowired
    @PersistenceContext(unitName = "entityManagerFactoryLocation")
    private EntityManager entityManager;

    public List<String> findAll(){
        String querySql = "SELECT Q_USER.USERNAME FROM Q_USER";
        Query query = this.entityManager.createNativeQuery(querySql);
        query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List resultList = query.getResultList();
        System.out.println(resultList);

        return resultList;
    }


}

10 Book1Service

package com.dmsoft.wavetide.service.service;


import com.dmsoft.wavetide.service.entity.User;

public interface Book1Service {

    void create(User user);
}


package com.dmsoft.wavetide.service.service.impl;

import com.dmsoft.wavetide.service.service.Book1Service;
import com.dmsoft.wavetide.service.feirepository.BookDao1;
import com.dmsoft.wavetide.service.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class Book1ServiceImpl implements Book1Service {

    @Autowired
    private BookDao1 bookDao1;
    @Override
    public void create(User user) {
        bookDao1.save(user);

    }
}

11 啟動(dòng)類

package com.dmsoft.wavetide.service;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;

@SpringBootApplication(scanBasePackages = {"com"})
@RestController
public class EmqdemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(EmqdemoApplication.class, args);
    }

}

12 配置文件

debug: true

spring:
   datasource:
      location:
         type: com.alibaba.druid.pool.DruidDataSource
         driver-class-name: oracle.jdbc.driver.OracleDriver
         url: jdbc:oracle:thin:@localhost:1521:orcl
         username: admin
         password: admin
      foreign:
         type: com.alibaba.druid.pool.DruidDataSource
         driver-class-name: com.mysql.cj.jdbc.Driver
         url: jdbc:mysql://localhost:3306/blueway?serverTimezone=UTC
         username: root
         password: root


   jpa:
      show-sql: true
   mvc:
      static-path-pattern: /api/static/**
   resources:
      static-locations: classpath:/static,classpath:/public,classpath:/resources,classpath:/META-INF/resources
   jackson:
      date-format: yyyy-MM-dd HH:mm:ss
      time-zone: GMT+8
   main:
      allow-bean-definition-overriding: true

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末约急,一起剝皮案震驚了整個(gè)濱河市零远,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌厌蔽,老刑警劉巖牵辣,帶你破解...
    沈念sama閱讀 221,273評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異奴饮,居然都是意外死亡纬向,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,349評(píng)論 3 398
  • 文/潘曉璐 我一進(jìn)店門戴卜,熙熙樓的掌柜王于貴愁眉苦臉地迎上來逾条,“玉大人,你說我怎么就攤上這事叉瘩∩排粒” “怎么了?”我有些...
    開封第一講書人閱讀 167,709評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵薇缅,是天一觀的道長危彩。 經(jīng)常有香客問我,道長泳桦,這世上最難降的妖魔是什么汤徽? 我笑而不...
    開封第一講書人閱讀 59,520評(píng)論 1 296
  • 正文 為了忘掉前任,我火速辦了婚禮灸撰,結(jié)果婚禮上谒府,老公的妹妹穿的比我還像新娘。我一直安慰自己浮毯,他們只是感情好完疫,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,515評(píng)論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著债蓝,像睡著了一般壳鹤。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上饰迹,一...
    開封第一講書人閱讀 52,158評(píng)論 1 308
  • 那天芳誓,我揣著相機(jī)與錄音,去河邊找鬼啊鸭。 笑死锹淌,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的赠制。 我是一名探鬼主播赂摆,決...
    沈念sama閱讀 40,755評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢(mèng)啊……” “哼!你這毒婦竟也來了库正?” 一聲冷哼從身側(cè)響起曲楚,我...
    開封第一講書人閱讀 39,660評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎褥符,沒想到半個(gè)月后龙誊,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,203評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡喷楣,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,287評(píng)論 3 340
  • 正文 我和宋清朗相戀三年趟大,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片铣焊。...
    茶點(diǎn)故事閱讀 40,427評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡逊朽,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出曲伊,到底是詐尸還是另有隱情叽讳,我是刑警寧澤,帶...
    沈念sama閱讀 36,122評(píng)論 5 349
  • 正文 年R本政府宣布坟募,位于F島的核電站岛蚤,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏懈糯。R本人自食惡果不足惜涤妒,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,801評(píng)論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望赚哗。 院中可真熱鬧她紫,春花似錦、人聲如沸屿储。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,272評(píng)論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽够掠。三九已至民褂,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間祖屏,已是汗流浹背助赞。 一陣腳步聲響...
    開封第一講書人閱讀 33,393評(píng)論 1 272
  • 我被黑心中介騙來泰國打工买羞, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留袁勺,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,808評(píng)論 3 376
  • 正文 我出身青樓畜普,卻偏偏與公主長得像期丰,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,440評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容