SpringBoot整合Mybatis多数据源

一、创建springboot项目并导入相关依赖

   

<dependency>

<groupId>com.alibaba</groupId>

<artifactId>druid-spring-boot-starter</artifactId>

<version>1.1.10</version>

</dependency>

   

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<scope>runtime</scope>

<version>5.1.27</version>

</dependency>

   

注:maven建议把mybatis的xml文件(也是mybatis查询写sql语句的xml)放在recourse文件下,所以运行的时候会跳过src/main/java下的xml,所以加上如下配置

   

SpringBoot整合Mybatis多数据源

<resources>

<resource>

<directory>src/main/java</directory>

<includes>

<include>**/*.xml</include>

</includes>

</resource>

<resource>

<directory>src/main/resouce</directory>

</resource>

</resources>

   

二、配置多数据相关设置

   

1.1

   

application.perteries文件

   

spring.datasource.one.type=com.alibaba.druid.pool.DruidDataSource

spring.datasource.one.url=jdbc:mysql://127.0.0.1:3306/jdbctemplates?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=GMT

spring.datasource.one.username=root

spring.datasource.one.password=123

   

spring.datasource.two.type=com.alibaba.druid.pool.DruidDataSource

spring.datasource.two.url=jdbc:mysql://127.0.0.1:3306/jdbctemplates2?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=GMT

spring.datasource.two.username=root

spring.datasource.two.password=123

   

1.2

   

创建三个配置类

SpringBoot整合Mybatis多数据源

   

DataSourceConfig类

   

@Configuration

publicclassDataSourceConfig{

@Bean

@ConfigurationProperties(prefix="spring.datasource.one")

DataSourcedataSourceOne(){

returnDruidDataSourceBuilder.create().build();

}

   

@Bean

@ConfigurationProperties(prefix="spring.datasource.two")

DataSourcedataSourceTwo(){

returnDruidDataSourceBuilder.create().build();

}

}

   

MyBatisConfigOne类

   

@Configuration

@MapperScan(basePackages="com.hufei.mybatis.mybatisdemo.mapper1",

sqlSessionFactoryRef="sqlSessionFactoryOne",

sqlSessionTemplateRef="sqlSessionTemplateOne")

publicclassMyBatisConfigOne{

@Autowired

@Qualifier("dataSourceOne")

privateDataSourcedataSourceOne;

   

@Bean

SqlSessionFactorysqlSessionFactoryOne(){

SqlSessionFactoryBeansqlSessionFactoryBean=newSqlSessionFactoryBean();

try{

sqlSessionFactoryBean.setDataSource(dataSourceOne);

returnsqlSessionFactoryBean.getObject();

}catch(Exceptione){

e.printStackTrace();

}

returnnull;

}

   

@Bean

SqlSessionTemplatesqlSessionTemplateOne(){

returnnewSqlSessionTemplate(sqlSessionFactoryOne());

}

}

   

MybatisConfigTwo类

   

同上

   

1.3

   

创建俩个Mapper

   

SpringBoot整合Mybatis多数据源

   

SpringBoot整合Mybatis多数据源

   

SpringBoot整合Mybatis多数据源

   

1.4

controller层

   

SpringBoot整合Mybatis多数据源

   

上一篇:idea 查看jar包依赖关系


下一篇:[无聊的事-连载之连开100个VS] 折腾你的骚机吧,骚年们!!!