【sping-boot】链接多个数据库源

修改配置文件

pom.xml中新增数据库配置

<?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.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>two-db-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>two-db-demo</name>
<description>Demo project for Spring Boot</description>

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

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>


<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>


<build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.7</version>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>

<configurationFile>src/main/resources/mybatis/generatorConfig.xml</configurationFile>
</configuration>

<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
</dependencies>
</plugin>
</plugins>

</build>

</project>

目录结构

 

mybatis配置相关 

generatorConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <context id="mysqlTables" targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="false"/>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!--目标数据库配置-->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                connectionURL="jdbc:mysql://localhost:3306/komo?useUnicode=true&characterEncoding=utf-8&useSSL=false&nullNamePatternMatchesAll=true"
                userId="root" password="123456"/>
        <!-- 指定生成的类型为java类型,避免数据库中number等类型字段 -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!-- 生成model模型,对应的包,存放位置可以指定具体的路径,如/ProjectName/src,也可以使用MAVEN来自动生成 -->
        <javaModelGenerator targetPackage="com.example.twodbdemo.dao.komoDao" targetProject="src/main/java">
            <property name="enableSubPackages" value="false"/>
            <property name="trimStrings" value="true"/>
            <property name="immutable" value="false"/>
        </javaModelGenerator>
        <!--对应的xml mapper文件  -->

        <sqlMapGenerator targetPackage="mapper"  targetProject="src/main/resources/mybatis/komo">
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>
        <!-- 对应的dao接口 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.example.twodbdemo.mapper.komoMapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="false"/>
        </javaClientGenerator>
        <!--定义需要操作的表及对应的DTO名称-->
        <table tableName="t_user" domainObjectName="User" />
    </context>
</generatorConfiguration>

 

启动类上新增 

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
package com.example.twodbdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;

// 去掉自动数据库自动配置类
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class TwoDbDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(TwoDbDemoApplication.class, args);
        System.out.println("========= Two Db Demo Application End ============");
    }
}

application数据库配置

先看application.yml中的配置

spring:
  datasource:
    db1:
      jdbc-url: jdbc:mysql://127.0.0.1:3306/komo?characterEncoding=utf-8
      username: root
      password: 123456
      driver-class-name: com.mysql.jdbc.Driver
    db2:
      jdbc-url: jdbc:mysql://127.0.0.1:3306/mfw?characterEncoding=utf-8
      username: root
      password: 123456
      driver-class-name: com.mysql.jdbc.Driver


server:
  port: 7777

config目录下的数据库配置

DataSourceConfig.java

package com.example.twodbdemo.config;

import javax.sql.DataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author komiles@163.com
 * @date 2020-05-09 14:18
 */
@Configuration
public class DataSourceConfig {

    @Bean(name="db1")
    @ConfigurationProperties(prefix = "spring.datasource.db1")
    public DataSource komoDbDataSource()
    {
        return DataSourceBuilder.create().build();
    }


    @Bean(name="db2")
    @ConfigurationProperties(prefix = "spring.datasource.db2")
    public DataSource mfwDbDataSource()
    {
        return DataSourceBuilder.create().build();
    }
}

Db1Config.java

package com.example.twodbdemo.config;

import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

/**
 * @author komiles@163.com
 * @date 2020-05-09 14:21
 */

@Configuration
@MapperScan(basePackages = {"com.example.twodbdemo.mapper.komoMapper"}, sqlSessionFactoryRef = "sqlSessionFactoryDb1")
public class Db1Config {

    private static final String PATH = "classpath:mybatis/komo/mapper/*.xml";

    @Autowired
    @Qualifier("db1")
    private DataSource dataSourceDb1;

    @Bean
    public SqlSessionFactory sqlSessionFactoryDb1() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSourceDb1);
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(Db1Config.PATH));
        return factoryBean.getObject();
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplateDb1() throws Exception {
        return new SqlSessionTemplate(sqlSessionFactoryDb1());
    }
}

 

Db2Config.java

package com.example.twodbdemo.config;

import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

/**
 * @author komiles@163.com
 * @date 2020-05-09 14:21
 */
@Configuration
@MapperScan(basePackages = {"com.example.twodbdemo.mapper.mfwMapper"}, sqlSessionFactoryRef = "sqlSessionFactoryDb2")
public class Db2Config {

    private static final String PATH = "classpath:mybatis/mfw/mapper/*.xml";

    @Autowired
    @Qualifier("db2")
    private DataSource dataSourceDb2;

    @Bean
    public SqlSessionFactory sqlSessionFactoryDb2() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSourceDb2);
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(Db2Config.PATH));
        return factoryBean.getObject();
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplateDb2() throws Exception {
        return new SqlSessionTemplate(sqlSessionFactoryDb2());
    }
}

 

 

Controller层文件

UserController.java

package com.example.twodbdemo.controller;

import com.example.twodbdemo.dao.komoDao.User;
import com.example.twodbdemo.dao.mfwDao.UserBase;
import com.example.twodbdemo.service.komo.UserService;
import com.example.twodbdemo.service.mfw.UserBaseService;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author komiles@163.com
 * @date 2020-05-09 14:39
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    UserBaseService userBaseService;

    @GetMapping("/komo/id")
    public User getOne(@RequestParam(value = "id") Integer id){
        return userService.getOne(id);
    }

    @GetMapping("/mfw/id")
    public UserBase getBaseOne(@RequestParam(value = "id") Integer id){
        return userBaseService.getOne(id);
    }

}

项目源码

地址:https://github.com/KoMiles/spring-example/tree/master/two-db-demo

posted @ 2020-05-11 14:17  KoMiles  阅读(549)  评论(0编辑  收藏  举报