SpringBoot增加Mybatis-plus并配置双数据源

2 篇文章 0 订阅
1 篇文章 0 订阅

MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

Mybatis-Plus官网地址

1.创建sb项目

2.添加MyBatis-Plus依赖

<!-- 以上省略sb的相关依赖,下面这个是web项目依赖 -->
<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- mybatis-plus依赖 -->
<dependency>
		<groupId>com.baomidou</groupId>
		<artifactId>mybatis-plus-boot-starter</artifactId>
		<version>3.0.6</version>
</dependency>

<!-- 连接池依赖+数据库驱动包依赖 -->
<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<scope>runtime</scope>
</dependency>
<dependency>
		<groupId>com.alibaba</groupId>
		<artifactId>druid</artifactId>
		<version>1.1.10</version>
</dependency>

3.添加配置类

两个数据源,我们这里配置两个类

 配置类1

package com.yanva.dm.common.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
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.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
@MapperScan (basePackages = DruidConfig.PACKAGE, sqlSessionFactoryRef = "sqlSessionFactory1")
public class DruidConfig {
    static final String PACKAGE = "com.yanva.dm.*.mapper";
    static final String MAPPER_LOCATION = "classpath:mapper/*/*.xml";


    @Bean("db1")
    @ConfigurationProperties(prefix = "spring.datasource.druid.master")
    public DataSource druidDataSource1() {
        DruidDataSource druidDataSource = new DruidDataSource();
        return druidDataSource;
    }

    @Bean("sqlSessionFactory1")
    public SqlSessionFactory sqlSessionFactory1(@Qualifier("db1")DataSource db1) throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(db1);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(DruidConfig.MAPPER_LOCATION));
        return sqlSessionFactoryBean.getObject();

    }




}

 配置类2

package com.yanva.dm.common.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
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.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
@MapperScan (basePackages = DruidConfig1.PACKAGE, sqlSessionFactoryRef = "sqlSessionFactory2")
public class DruidConfig1 {
    static final String PACKAGE = "com.yanva.dm.slavedb.*.mapper";
    static final String MAPPER_LOCATION = "classpath:mapper/slavedb/*.xml";

    @Bean("db2")
    @ConfigurationProperties(prefix = "spring.datasource.druid.slave")
    public DataSource druidDataSource1() {
        DruidDataSource druidDataSource = new DruidDataSource();
        return druidDataSource;
    }

    @Bean("sqlSessionFactory2")
    public SqlSessionFactory sqlSessionFactory1(@Qualifier("db2")DataSource db2) throws Exception {
        MybatisSqlSessionFactoryBean  sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(db2);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(DruidConfig1.MAPPER_LOCATION));
        return sqlSessionFactoryBean.getObject();

    }




}

 * 注意 PACKAGE 和MAPPER_LOCATION 还有 @ConfigurationProperties(prefix = "spring.datasource.druid.slave")

    都需要根据具体情况配置。

 

4.修改application.yml文件(对数据源的配置和mybatis-plus的配置)

 

server:
  port: 9898
spring:
  datasource:
    name: druidDataSource
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      master:
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/home?allowMultiQueries=true&useUnicode=true&serverTimezone=UTC&characterEncoding=UTF-8&useSSL=false
        username: root
        password: root
        initial-size: 10
        max-active: 100
        min-idle: 10
        max-wait: 60000
        pool-prepared-statements: true
        max-pool-prepared-statement-per-connection-size: 20
        time-between-eviction-runs-millis: 60000
        min-evictable-idle-time-millis: 300000
        test-while-idle: true
        test-on-borrow: false
        test-on-return: false
      slave:
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/yinzi_database?allowMultiQueries=true&useUnicode=true&serverTimezone=UTC&characterEncoding=UTF-8&useSSL=false
        username: root
        password: root

        initial-size: 10
        max-active: 100
        min-idle: 10
        max-wait: 60000
        pool-prepared-statements: true
        max-pool-prepared-statement-per-connection-size: 20
        time-between-eviction-runs-millis: 60000
        min-evictable-idle-time-millis: 300000

        test-while-idle: true
        test-on-borrow: false
        test-on-return: false
  freemarker:
    template-loader-path: classpath:templates/
    suffix: .ftl

mybatis-plus:
  mapper-locations: classpath:dao/*Mapper.xml
  type-aliases-package: com.yanva.dm.entity

* 注意 yml文件中,属性和值一定要有空格,还要格外注意缩进,同等级的,缩进必须一致。

* 注意 两个数据源的表不可以是同名的 ,不同数据源所对应的mapper文件也需要放在不同的包中。因为框架是通过映射关系来自动区分数据源的

  • 7
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
配置数据源: 1. 在pom.xml中添加mybatis-plus和druid依赖: ```xml <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.3.1</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.6</version> </dependency> ``` 2. 在application.yml中添加数据源配置: ```yaml spring: datasource: druid: one: url: jdbc:mysql://localhost:3306/one?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver two: url: jdbc:mysql://localhost:3306/two?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource #默认数据源 primary: one ``` 3. 在代码中使用@DS注解切换数据源: ```java @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @DS("one") @Override public User getUserById(Long id) { return userMapper.selectById(id); } @DS("two") @Override public User getUserByName(String name) { return userMapper.selectOne(new QueryWrapper<User>().eq("name", name)); } } ``` 配置分页插件: 1. 在pom.xml中添加分页插件依赖: ```xml <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.3.1</version> </dependency> ``` 2. 在配置类中配置分页插件: ```java @Configuration public class MybatisPlusConfig { @Bean public PaginationInterceptor paginationInterceptor() { PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); return paginationInterceptor; } } ``` 3. 在controller层中使用分页: ```java @GetMapping("/users") public IPage<User> getUsers(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) { Page<User> page = new Page<>(pageNum, pageSize); QueryWrapper<User> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("status", 1); return userService.page(page, queryWrapper); } ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值