springboot干货——(十二)多数据源配置之mybatis

xiaoxiao2021-04-18  15

关于多数据源的配置之前有整合过jdbc和springdata,但是这两种情况在实际的项目中用的不是很多,主要原因是jdbc的sql语句需要自己来写,后期维护什么的不是很好;springdata这块国内用的不是很多,相对而言坑比较多,一般企业级开发不是很敢用。本篇博客主要讲基于整合mybatis的多数据源配置。在写这篇博客之前也大致在网上看了一些资料,综合了这些资料进行了一个取长补短的配置,保证了代码在能够运行的同时更加简单。

 

正文

1.老规矩,先来看下项目结构图

 

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

<modelVersion>4.0.0</modelVersion>

 

<groupId>spring-boot</groupId>

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

<version>0.0.1-SNAPSHOT</version>

<packaging>jar</packaging>

 

<name>spring-boot-mybatis</name>

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

 

<parent>

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

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

<version>1.5.9.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.mybatis.spring.boot</groupId>

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

<version>1.3.1</version>

</dependency>

 

<dependency>

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

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

<scope>test</scope>

</dependency>

<dependency>

<groupId>mysql</groupId>

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

</dependency>

<dependency>

<groupId>com.alibaba</groupId>

<artifactId>druid</artifactId>

<version>1.0.29</version>

</dependency>

<dependency>

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

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

</dependency>

</dependencies>

 

<build>

<plugins>

<plugin>

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

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

</plugin>

</plugins>

</build>

</project>

3.application.properties

 

 

spring.datasource.primary.url=jdbc:mysql://localhost:3306/test

spring.datasource.primary.username=root

spring.datasource.primary.password=19940315

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

 

spring.datasource.secondary.url=jdbc:mysql://localhost:3306/myweb

spring.datasource.secondary.username=root

spring.datasource.secondary.password=19940315

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

4.DataSourceConfig

【注意】@ConfigurationProperties:把配置文件的信息,读取并自动封装成实体类,无需进行set

 

 

package com.gwd.config;

 

import javax.sql.DataSource;

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

import org.springframework.boot.context.properties.ConfigurationProperties;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.context.annotation.Primary;

/**

* @ProjectName spring-boot-datas-jpa

* @author JackHisen(gu.weidong)

* @Date 2018年2月16日 下午1:49:13

* @Version 1.0

* @Description:

*/

@Configuration

public class DataSourceConfig {

 

@Bean(name = "primaryDataSource")

@Qualifier("primaryDataSource")

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

public DataSource primaryDataSource() {

DataSource dataSource = new com.alibaba.druid.pool.DruidDataSource();

return dataSource;

}

 

@Bean(name = "secondaryDataSource")

@Qualifier("secondaryDataSource")

@Primary

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

public DataSource secondaryDataSource() {

DataSource dataSource = new com.alibaba.druid.pool.DruidDataSource();

return dataSource;

}

}

PrimaryConfig:

【注意】这边设置了mapper的扫描路径,已经mapper.xml的位置

 

 

package com.gwd.config;

 

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;

import org.mybatis.spring.SqlSessionFactoryBean;

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.context.annotation.Primary;

import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import org.springframework.jdbc.datasource.DataSourceTransactionManager;

/**

* @ProjectName spring-boot-mybatis

* @author JackHisen(gu.weidong)

* @Date 2018年2月16日 下午9:52:48

* @Version 1.0

* @Description:

*/

@Configuration

//扫描 Mapper 接口并容器管理

@MapperScan(basePackages = PrimaryConfig.PACKAGE, sqlSessionFactoryRef = "masterSqlSessionFactory")

public class PrimaryConfig {

 

// 精确到 master 目录,以便跟其他数据源隔离

static final String PACKAGE = "com.gwd.mapper.stu";

static final String MAPPER_LOCATION = "classpath:mapper/stu/*.xml";

 

@Autowired

@Qualifier("primaryDataSource")

private DataSource primaryDataSource;

  

@Bean(name = "masterTransactionManager")

@Primary

public DataSourceTransactionManager masterTransactionManager() {

return new DataSourceTransactionManager(primaryDataSource);

}

 

@Bean(name = "masterSqlSessionFactory")

@Primary

public SqlSessionFactory masterSqlSessionFactory(@Qualifier("primaryDataSource") DataSource primaryDataSource)

throws Exception {

final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();

sessionFactory.setDataSource(primaryDataSource);

sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()

.getResources(PrimaryConfig.MAPPER_LOCATION));

return sessionFactory.getObject();

}

}

 

SecondaryConfig:

 

package com.gwd.config;

 

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;

import org.mybatis.spring.SqlSessionFactoryBean;

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;

import org.springframework.jdbc.datasource.DataSourceTransactionManager;

/**

* @ProjectName spring-boot-mybatis

* @author JackHisen(gu.weidong)

* @Date 2018年2月16日 下午10:06:12

* @Version 1.0

* @Description:

*/

@Configuration

//扫描 Mapper 接口并容器管理

@MapperScan(basePackages = SecondaryConfig.PACKAGE, sqlSessionFactoryRef = "clusterSqlSessionFactory")

public class SecondaryConfig {

 

// 精确到 cluster 目录,以便跟其他数据源隔离

static final String PACKAGE = "com.gwd.mapper.user";

static final String MAPPER_LOCATION = "classpath:mapper/user/*.xml";

@Autowired

@Qualifier("secondaryDataSource")

private DataSource secondaryDataSource;

 

@Bean(name = "clusterTransactionManager")

public DataSourceTransactionManager clusterTransactionManager() {

return new DataSourceTransactionManager(secondaryDataSource);

}

 

@Bean(name = "clusterSqlSessionFactory")

public SqlSessionFactory clusterSqlSessionFactory(@Qualifier("secondaryDataSource") DataSource secondaryDataSource)

throws Exception {

final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();

sessionFactory.setDataSource(secondaryDataSource);

sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()

.getResources(SecondaryConfig.MAPPER_LOCATION));

return sessionFactory.getObject();

}

}

5.model层

model层是mybatis的逆向工具自动生成

 

6.dao层【均是自动生成】

stuMapper:

 

 

package com.gwd.mapper.stu;

 

import com.gwd.model.stu.Stu;

public interface StuMapper {

Stu selectByPrimaryKey(Integer id);

}

 

userMapper:

 

 

package com.gwd.mapper.user;

 

import com.gwd.model.user.User;

 

public interface UserMapper {

User selectByPrimaryKey(Integer id);

}

 

7.service(忽略代码)和service实现类

【注意】不能忘了@service注解 stuServiceImpl:

 

 

package com.gwd.service.impl;

 

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

import org.springframework.stereotype.Service;

import com.gwd.mapper.stu.StuMapper;

import com.gwd.model.stu.Stu;

import com.gwd.service.StuService;

/**

* @ProjectName spring-boot-mybatis

* @author JackHisen(gu.weidong)

* @Date 2018年2月16日 下午10:10:25

* @Version 1.0

* @Description:

*/

@Service

public class StuServiceImpl implements StuService{

@Autowired

StuMapper stuMapper;

@Override

public Stu getStuById(int id) {

Stu stu = stuMapper.selectByPrimaryKey(id);

return stu;

}

}

 

userServiceImpl:

 

 

package com.gwd.service.impl;

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

/**

* @ProjectName spring-boot-mybatis

* @author JackHisen(gu.weidong)

* @Date 2018年2月16日 下午10:09:43

* @Version 1.0

* @Description:

*/

import org.springframework.stereotype.Service;

import com.gwd.mapper.user.UserMapper;

import com.gwd.model.user.User;

import com.gwd.service.UserService;

 

@Service

public class UserServiceImpl implements UserService{

@Autowired

UserMapper userMapper;

@Override

public User getUserById(int id) {

User user = userMapper.selectByPrimaryKey(id);

return user;

}

}

8.controller

 

 

package com.gwd.controller;   import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.gwd.model.stu.Stu; import com.gwd.model.user.User; import com.gwd.service.StuService; import com.gwd.service.UserService;   /**  * @ProjectName spring-boot-mybatis * @author JackHisen(gu.weidong)  * @Date 2018年2月16日 下午9:54:52     * @Version 1.0  * @Description: */ @RestController public class TestController {     @Autowired     UserService userService;          @Autowired     StuService stuService;          @RequestMapping("getUser")     public String getUser() {         User user = userService.getUserById(6);         return user.getUsername();     }          @RequestMapping("getStu")     public String getStu() {         Stu stu = stuService.getStuById(1);         return stu.getName();     } }  

 

9.结果:成功!!!

 

 

--------------------- 作者:东天里的冬天 来源: 原文:https://blog.csdn.net/gwd1154978352/article/details/79331176?utm_source=copy 版权声明:本文为博主原创文章,转载请附上博文链接!