springboot+mybatis整合实现多数据源

springboot+mybatis整合实现多数据源

创建项目

1.访问http://start.spring.io/下载项目压缩包;

2.解压后,使用eclipse,Import -> Existing Maven Projects -> Next ->选择解压后的文件夹-> Finsh

项目结构如下(此结构为实现后的项目结构):

 

 

数据库配置

有两个数据库,每个数据库都有一个user表(表结构都一样),如下:

 

 

 

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 http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>

 

   <groupId>com.example</groupId>

   <artifactId>datasource</artifactId>

   <version>0.0.1-SNAPSHOT</version>

   <packaging>jar</packaging>

 

   <name>datasource</name>

   <description>Demo project for Spring Boot</description>

 

   <parent>

      <groupId>org.springframework.boot</groupId>

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

      <version>2.0.2.RELEASE</version>

      <relativePath/> <!-- lookup parent from repository -->

   </parent>

 

   <properties>

      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

   <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

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

   </properties>

 

   <dependencies>

      <dependency>

        <groupId>org.springframework.boot</groupId>

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

      </dependency>

 

      <dependency>

        <groupId>org.springframework.boot</groupId>

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

        <scope>test</scope>

      </dependency>

     

      <!-- 启动web项目 -->

      <dependency>

            <groupId>org.springframework.boot</groupId>

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

        </dependency>

       

        <dependency>

        <groupId>org.mybatis.spring.boot</groupId>

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

        <version>1.1.1</version>

      </dependency>

      <dependency>

        <groupId>mysql</groupId>

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

        <version>5.1.21</version>

      </dependency>

     

   </dependencies>

 

   <build>

      <plugins>

        <plugin>

           <groupId>org.springframework.boot</groupId>

           <artifactId>spring-boot-maven-plugin</artifactId>

        </plugin>

      </plugins>

   </build>

</project>

application.properties配置

spring.datasource.test1.driver-class-name = com.mysql.jdbc.Driver

spring.datasource.test1.jdbc-url = jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8

spring.datasource.test1.username = root

spring.datasource.test1.password = 123456

 

spring.datasource.test2.driver-class-name = com.mysql.jdbc.Driver

spring.datasource.test2.jdbc-url = jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8

spring.datasource.test2.username = root

spring.datasource.test2.password = 123456

 

mapper文件配置:

UserMapperTest01.xml

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

 

<mapper namespace="com.example.datasource.test01.dao.UserMapperTest01">

    <insert id="insert">

       INSERT INTO USER(USERNAME,BIRTHDAY,SEX,ADDRESS) VALUES(#{0},'2018-06-03', #{1},#{2})

   </insert>

</mapper>

 

UserMapperTest02.xml

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.example.datasource.test02.dao.UserMapperTest02">

    <insert id="insert">

       INSERT INTO USER(USERNAME,BIRTHDAY,SEX,ADDRESS) VALUES(#{0},'2018-06-03', #{1},#{2})

   </insert>

</mapper>

UserMapperTest01.java

package com.example.datasource.test01.dao;

 

import org.springframework.cache.annotation.CacheConfig;

 

@CacheConfig(cacheNames = "baseCache")

public interface UserMapperTest01 {

   int insert(String username, Integer sex, String address);

}

UserMapperTest02.java

package com.example.datasource.test02.dao;

 

public interface UserMapperTest02 {

   int insert(String username, Integer sex, String address);

}

User.java

package com.example.datasource.entity;

 

public class User {

 

   private Integer id;

 

   private String username;

 

   private Integer sex;

 

   public Integer getId() {

      return id;

   }

 

   public void setId(Integer id) {

      this.id = id;

   }

 

   public String getUsername() {

      return username;

   }

 

   public void setUsername(String username) {

      this.username = username;

   }

 

   public Integer getSex() {

      return sex;

   }

 

   public void setSex(Integer sex) {

      this.sex = sex;

   }

}

DataSource1Config.java

package com.example.datasource.datasource;

 

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.Qualifier;

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;

import org.springframework.context.annotation.Primary;

import org.springframework.jdbc.datasource.DataSourceTransactionManager;

 

//注册到springboot容器中

@Configuration

@MapperScan(basePackages = "com.example.datasource.test01", sqlSessionFactoryRef = "test1SqlSessionFactory")

public class DataSource1Config {

 

   @Bean(name = "test1DataSource")

   @Primary

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

   public DataSource testDataSource() {

      return DataSourceBuilder.create().build();

   }

 

   @Bean(name = "test1SqlSessionFactory")

   @Primary

   public SqlSessionFactory testSqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource)

        throws Exception {

      SqlSessionFactoryBean bean = new SqlSessionFactoryBean();

      bean.setDataSource(dataSource);

      return bean.getObject();

   }

 

   @Bean(name = "test1TransactionManager")

   @Primary

   public DataSourceTransactionManager testTransactionManager(@Qualifier("test1DataSource") DataSource dataSource) {

      return new DataSourceTransactionManager(dataSource);

   }

 

   @Bean(name = "test1SqlSessionTemplate")

   public SqlSessionTemplate testSqlSessionTemplate(

        @Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {

      return new SqlSessionTemplate(sqlSessionFactory);

   }

 

}

DataSource2Config.java

package com.example.datasource.datasource;

 

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.Qualifier;

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;

import org.springframework.jdbc.datasource.DataSourceTransactionManager;

 

//注册到springboot容器中

@Configuration

@MapperScan(basePackages = "com.example.datasource.test02", sqlSessionFactoryRef = "test2SqlSessionFactory")

public class DataSource2Config {

 

   @Bean(name = "test2DataSource")

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

   public DataSource testDataSource() {

      return DataSourceBuilder.create().build();

   }

 

   @Bean(name = "test2SqlSessionFactory")

   public SqlSessionFactory testSqlSessionFactory(@Qualifier("test2DataSource") DataSource dataSource)

        throws Exception {

      SqlSessionFactoryBean bean = new SqlSessionFactoryBean();

      bean.setDataSource(dataSource);

      return bean.getObject();

   }

 

   @Bean(name = "test2TransactionManager")

   public DataSourceTransactionManager testTransactionManager(@Qualifier("test2DataSource") DataSource dataSource) {

      return new DataSourceTransactionManager(dataSource);

   }

 

   @Bean(name = "test2SqlSessionTemplate")

   public SqlSessionTemplate testSqlSessionTemplate(

        @Qualifier("test2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {

      return new SqlSessionTemplate(sqlSessionFactory);

   }

 

}

DataSourceController.java

 

package com.example.datasource.controller;

 

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

 

import com.example.datasource.test01.dao.UserMapperTest01;

import com.example.datasource.test02.dao.UserMapperTest02;

 

@Controller

public class DataSourceController {

 

 

   @Autowired

   private UserMapperTest01 userMapperTest01;

   @Autowired

   private UserMapperTest02 userMapperTest02;

 

 

   @ResponseBody

   @RequestMapping("/insertTest001")

   public String insertTest001(String username, Integer sex) {

      userMapperTest01.insert(username, sex,"北京市");

      return "success";

   }

 

   @ResponseBody

   @RequestMapping("/insertTest002")

   public String insertTest002(String username, Integer sex) {

      userMapperTest02.insert(username, sex, "安康市");

      return "success";

   }

}

 

启动类:

package com.example.datasource;

 

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

 

@SpringBootApplication

public class DatasourceApplication {

 

   public static void main(String[] args) {

      SpringApplication.run(DatasourceApplication.class, args);

   }

}

 

测试:

启动启动类,启动后,打开浏览器分别执行:

http://localhost:8080/insertTest001?username=wcj001&sex=1

 

http://localhost:8080/insertTest001?username=wcj001&sex=1

 

发现两个数据库里都插入了数据

posted @ 2018-06-03 15:58  零秒思考  阅读(220)  评论(0编辑  收藏  举报