SpringBoot整合Mybatis多数据源

时间:2021-02-23 07:51:43

SpringBoot整合Mybatis多数据源

我们平时操作的都是操作单个数据库,那么我们今天来学习一下,springboot如何整合mybatis操作多数据源,源码以及过程都非常详细,供大家参考!


1.SQL数据

DROP TABLE IF EXISTS `users1`;

CREATE TABLE `users1` (

  `id` bigint(20) NOT NULL AUTO_INCREMENT,

  `userName` varchar(20) DEFAULT NULL,

  `passWord` varchar(20) DEFAULT NULL,

  PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

 

2.Pom配置文件中映入

<!-- 必须引用 springboot父工程依赖 -->

<parent>

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

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

<version>1.5.4.RELEASE</version>

</parent>

<!-- 环境配置 -->

<properties>

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

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

</properties>

<dependencies>

<!-- springweb工程依赖 默认继承SpringMVC -->

<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>

<dependency>

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

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

</dependency>

<dependency>

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

<artifactId>spring-boot-devtools</artifactId>

<optional>true</optional>

</dependency>

<!-- 引入springboot整合mybatis注解-->

<dependency>

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

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

<version>1.1.1</version>

</dependency>

<!-- MySQL数据库连接驱动 -->

<dependency>

<groupId>mysql</groupId>

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

</dependency>

</dependencies>

 

<!-- SpringBoot maven运行编译环境 -->

<build>

<plugins>

<plugin>

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

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

</plugin>

<!-- 构建节点 -->

<plugin>

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

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

<dependencies>

<!--在这里添加 springloader plugin -->

<dependency>

<groupId>org.springframework</groupId>

<artifactId>springloaded</artifactId>

<version>1.2.4.RELEASE</version>

</dependency>

</dependencies>

<executions>

<execution>

<goals>

<goal>repackage</goal>

</goals>

<configuration>

<classifier>exec</classifier>

</configuration>

</execution>

</executions>

</plugin>

</plugins>

</build>

3.application.properties配置文件新增多数据源配置

mybatis.config-locations=classpath:mybatis/mybatis-config.xml

 

spring.datasource.test1.driverClassName = com.mysql.jdbc.Driver

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

spring.datasource.test1.username = root

spring.datasource.test1.password = root

 

spring.datasource.test2.driverClassName = com.mysql.jdbc.Driver

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

spring.datasource.test2.username = root

spring.datasource.test2.password = root

一个 test1 库和一个test2 库,其中test1 位主库,在使用的过程中必须制定主库,不然会报错。

4.数据源配置

/**

 * db1数据源配置

 *

 */

@Configuration

@MapperScan(basePackages = "com.wangys.mapper.test1", sqlSessionTemplateRef  = "test1SqlSessionTemplate")

public class DataSource1Config {

 

/**

 * 创建数据源,读取配置文件开头spring.datasource.test1信息

 */

    @Bean(name = "test1DataSource")

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

    @Primary

    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);

        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test1/*.xml"));

        return bean.getObject();

    }

    

    /*

     * 创建test1数据事务管理器

     */

    @Bean(name = "test1TransactionManager")

    @Primary

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

        return new DataSourceTransactionManager(dataSource);

    }

 

    /*

     * 创建test1会话模板

     */

    @Bean(name = "test1SqlSessionTemplate")

    @Primary

    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {

        return new SqlSessionTemplate(sqlSessionFactory);

    }

 

}

注意:最关键的地方就是这块了,一层一层注入, 先创建 DataSource,再创建SqlSessionFactory ,再创建事务,最后包装到SqlSessionTemplate 中。其中需要制定分库的mapper 文件地址,以及分库到层代码

@MapperScan(basePackages = "com.neo.mapper.test1", sqlSessionTemplateRef  = "test1SqlSessionTemplate")

这块的注解就是指明了扫描 dao 层,并且给 dao 层注入指定的SqlSessionTemplate。所有@Bean都需要按照命名指定正确。

5.创建实体类

6.创建两个不同的mapper层包

dao 层和 xml需要按照库来分在不同的目录,比如:

test1 dao com.neo.mapper.test1包下

test2 dao层在 com.neo.mapper.test2包下

public interface User1Mapper {

 

List getAll();

 

UserEntity getOne(Long id);

 

void insert(UserEntity user);

 

void update(UserEntity user);

 

void delete(Long id);

 

}

 

xml

id, userName, passWord SELECT FROM users

SELECT FROM users WHERE id = #{id}

INSERT INTO users (userName,passWord) VALUES (#{userName}, #{passWord})

UPDATE users SET userName = #{userName}, passWord = #{passWord} WHERE id = #{id}

DELETE FROM users WHERE id =#{id}

 

7.测试

Controller层:

@RestController

public class UsersController {

 

@Autowired

private Users1Mapper users1Mapper;

@Autowired

private Users2Mapper users2Mapper;

@RequestMapping("/addTest01")

public String addTest1(UserEntity userEntity){

users1Mapper.adduser(userEntity);

return "success";

}

@RequestMapping("/addTest02")

public String addTest2(UserEntity userEntity){

users2Mapper.adduser(userEntity);

return "success";

}

}

main层:

@SpringBootApplication(exclude={DataSourceAutoConfiguration.class,HibernateJpaAutoConfiguration.class})

@ComponentScan(basePackages={"com.wangys.controller","com.wangys.datasource"})

public class Main {

public static void main(String[] args) {

SpringApplication.run(Main.class, args);

}

}

 

异常:Cannot determine embedded database driver class for database type NONE

原因是:springboot 启动时会自动注入数据源和配置 jpa

解决:在 @SpringBootApplication 中排除其注入

@SpringBootApplication(exclude={DataSourceAutoConfiguration.class,HibernateJpaAutoConfiguration.class})

 

8.运行结果

 SpringBoot整合Mybatis多数据源SpringBoot整合Mybatis多数据源