栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot 整合MyBatis-Plus 详细教程,配置多数据源并支持事务,附带代码生成器使用教程

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot 整合MyBatis-Plus 详细教程,配置多数据源并支持事务,附带代码生成器使用教程

SpringBoot 整合MyBatis-Plus 详细教程,配置多数据源并支持事务,附带代码生成器使用教程

一.在pom.xml加入依赖,如下



    mysql
    mysql-connector-java
    runtime



    com.baomidou
    mybatis-plus-boot-starter
    3.3.1



    com.baomidou
    dynamic-datasource-spring-boot-starter
    3.1.0



    com.baomidou
    mybatis-plus-generator
    3.3.1.tmp



    org.apache.velocity
    velocity-engine-core
    2.2



    org.freemarker
    freemarker
    2.3.29

二.在application.yml配置多数据源,mybatis-plus相关配置

spring:
  # 配置数据源
  datasource:
    dynamic:
      primary: db1 # 设置默认的数据源或者数据源组,默认值即为master
      datasource:
        db1:
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://xxx:3306/mybatisplus_demo?useUnicode=true&characterEncoding=utf-8
          username: xxx
          password: xxx
          # hikari
          hikari:
            connection-test-query: SELECt 1
            ## 最小空闲连接数量
            minimum-idle: 5
            ## 连接池最大连接数,默认是10
            maximum-pool-size: 15
            ## 连接池名称
            pool-name: MyHikariCPOfMaster
            ## 此属性控制池中连接的最长生命周期,值0表示无限生命周期,默认1800000即30分钟
            max-lifetime: 1800000
            ## 数据库连接超时时间,默认30秒,即30000
            connection-timeout: 20000
            ## 空闲连接存活最大时间,默认600000(10分钟)
            idle-timeout: 180000
            ## 此属性控制从池返回的连接的默认自动提交行为,默认值:true
            auto-commit: true
        db2:
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://xxx:3306/mybatisplus_demo?useUnicode=true&characterEncoding=utf-8
          username: xxx
          password: xxx
          # hikari
          hikari:
            connection-test-query: SELECT 1
            ## 最小空闲连接数量
            minimum-idle: 5
            ## 连接池最大连接数,默认是10
            maximum-pool-size: 15
            ## 连接池名称
            pool-name: MyHikariCPOfMaster
            ## 此属性控制池中连接的最长生命周期,值0表示无限生命周期,默认1800000即30分钟
            max-lifetime: 1800000
            ## 数据库连接超时时间,默认30秒,即30000
            connection-timeout: 20000
            ## 空闲连接存活最大时间,默认600000(10分钟)
            idle-timeout: 180000
            ## 此属性控制从池返回的连接的默认自动提交行为,默认值:true
            auto-commit: true

# mybatis-plus相关配置
mybatis-plus:
  # xml扫描,多个目录用逗号或者分号分隔(告诉 Mapper 所对应的 XML 文件位置)
  mapper-locations: classpath:com/luoyu/mybatisplus/mapper/xml
//    @Bean
//    @Profile({"dev", "qa"})
//    public PerformanceInterceptor performanceInterceptor() {
//        PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
//        performanceInterceptor.setMaxTime(1000);
//        performanceInterceptor.setFormat(true);
//        return performanceInterceptor;
//    }

    
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        // 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求  默认false
         paginationInterceptor.setOverflow(false);
        // 设置最大单页限制数量,默认 500 条,-1 不受限制
         paginationInterceptor.setLimit(500);
        // 开启 count 的 join 优化,只针对部分 left join
        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
        return paginationInterceptor;
    }
}

五. 踩坑!!!如果xml文件没有放在resources目录下的话,需要在pom.xml文件的标签里面新增以下配置,否则就算在application.yml文件配置了扫描xml文件的路径也没用,小坑!!!


    
        src/main/java
        
        
            **/*.xml
        
    

六.在启动类MybatisplusApplication新增@MapperScan注解,里面写入生成的文件中的mapper存放的路径,用于扫描mapper文件。到此springboot2.2.5 整合MyBatis-Plus3.3.1 完毕,直接在mapper文件写sql语句,在service文件调用即可。

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@MapperScan("com.luoyu.mybatisplus.mapper")
@SpringBootApplication
public class MybatisplusApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatisplusApplication.class, args);
    }

}

七. 新增自定义的sql方法,编写IUserService,UserServiceImpl,UserMapper,UserMapper.xml用于操作数据源db1;ITaskService,TaskServiceImpl,TaskMapper,TaskMapper.xml用于操作数据源db2,分别如下
注:
在UserServiceImpl,TaskServiceImpl中,@DS()注解代表指定各自的数据源,@Transactional注解代表开启Spring事务。

数据源db1,IUserService

import com.baomidou.mybatisplus.extension.service.IService;
import com.luoyu.mybatisplus.entity.User;


public interface IUserService extends IService {

   
    User selectByName(String name);

   
    int updateName(int id, String name);

}

UserServiceImpl

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.luoyu.mybatisplus.entity.User;
import com.luoyu.mybatisplus.mapper.UserMapper;
import com.luoyu.mybatisplus.service.IUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@DS("db1")
@Service
public class UserServiceImpl extends ServiceImpl implements IUserService {

    @Resource
    private UserMapper userMapper;

    
    @Override
    public User selectByName(String name) {
        return userMapper.selectByName(name);
    }

   
    @Transactional
    @Override
    public int updateName(int id, String name) {
        int n = userMapper.updateName(id, name);
        // 此处报错事务回滚
        int i = 1/0;
        return n;
    }
}

UserMapper

import com.baomidou.mybatisplus.core.mapper.baseMapper;
import com.luoyu.mybatisplus.entity.User;
import org.apache.ibatis.annotations.Param;


public interface UserMapper extends baseMapper {

    
    User selectByName(String name);

    
    int updateName(@Param("id") int id, @Param("name") String name);

}

UserMapper.xml





    
        select * from task where name = #{name};
    

    
        update task set name = #{name} where id = #{id};
    
    

八. 编写单元测试类,MybatisplusApplicationTests,并进行测试,只列举了部分方法

import com.luoyu.mybatisplus.entity.Task;
import com.luoyu.mybatisplus.entity.User;
import com.luoyu.mybatisplus.service.ITaskService;
import com.luoyu.mybatisplus.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@Slf4j
// 获取启动类,加载配置,确定装载 Spring 程序的装载方法,它回去寻找 主配置启动类(被 @SpringBootApplication 注解的)
@SpringBootTest
class MybatisplusApplicationTests {

    @Autowired
    private IUserService iUserService;

    @Autowired
    private ITaskService iTaskService;

    @Test
    void selectApiTest() {
        log.info("使用MP提供的CRUD");
        User user = iUserService.getById("1");
        log.info(user.toString());
    }

    @Test
    void selectDb1Test() {
        // 验证多数据源db1
        log.info("使用自定义的方法,查看db1");
        User user = iUserService.selectByName("Jack");
        log.info(user.toString());
    }

    @Test
    void selectDb2Test() {
        // 验证多数据源db2
        log.info("使用自定义的方法,查看db2");
        Task task = iTaskService.selectByName("韩信");
        log.info(task.toString());
    }

    @Test
    void updateDb1Test() {
        // 验证事务
        iUserService.updateName(1, "改名啦");
    }

    @BeforeEach
    void testBefore(){
        log.info("测试开始!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    }

    @AfterEach
    void testAfter(){
        log.info("测试结束!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    }

}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/322245.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号