最近进行的项目有需求要连接两台数据库,由于之前没有进行过这样的操作所以查找了很多博客,发现都是需要配置xml文件的,而我并没有使用xml文件,所以踩了很多坑。
以下是连接两个数据源的demo
1、先在启动类中禁用自动选择数据源
package com.example.demo;
import com.github.pagehelper.PageHelper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.Properties;
//禁用自动获取数据源
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@MapperScan("com.example.demo.*")
@EnableSwagger2 //启动swagger注解
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
//配置mybatis的分页插件pageHelper
@Bean
public PageHelper pageHelper() {
PageHelper pageHelper = new PageHelper();
Properties properties = new Properties();
properties.setProperty("offsetAsPageNum", "true");
properties.setProperty("rowBoundsWithCount", "true");
properties.setProperty("reasonable", "true");
properties.setProperty("dialect", "mysql"); //配置mysql数据库的方言
pageHelper.setProperties(properties);
return pageHelper;
}
}
2、在application.yml文件中添加两个数据源 ,如果是.propertity
#application.yml
spring:
datasource:
test1:
driverClassName: com.mysql.jdbc.Driver
jdbc-url: jdbc:mysql://localhost:3306/taizhouyuqing?useUnicode=true&characterEncoding=utf8&useSSL=false
username: root
password: rootroot
#mybatis.config-location=classpath:mybatis-config.xml
#
max-active: 20
max-idle: 8
min-idle: 8
initial-size: 10
mvc:
static-path-pattern: /static/**
test2:
driverClassName: com.mysql.jdbc.Driver
jdbc-url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false
username: root
password: rootroot
#mybatis.config-location=classpath:mybatis-config.xml
#
max-active: 20
max-idle: 8
min-idle: 8
initial-size: 10
mvc:
static-path-pattern: /static/**
swagger:
basePackage: com.metadatamanage.controler
title: MetadataManageAPI
description: Metadata Manage API。
version: V1.0