springboot+mybatisplus(含动态数据源,sql打印,分页,代码自动生成)

pom文件



	4.0.0
	
		com.sonhai.springboot
		boot-parent
		1.0-SNAPSHOT
		 
	
	boot-mybatis
	0.0.1-SNAPSHOT
	boot-mybatis
	Demo project for Spring Boot

	
		
			org.springframework.boot
			spring-boot-starter-web
		

		
			org.springframework.boot
			spring-boot-starter-test
			test
		

		
			
			
			
		

		
			com.baomidou
			mybatis-plus-boot-starter
			3.2.0
		

		
			com.baomidou
			mybatis-plus-generator
			3.2.0
		

		
		
			org.freemarker
			freemarker
			2.3.29
		

		
		
			p6spy
			p6spy
			LATEST
		

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

		
			mysql
			mysql-connector-java
		
	



配置文件

server.port=8092

#spring.datasource.url=jdbc:p6spy:mysql://120.11.111.111:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
#spring.datasource.username=root
#spring.datasource.password=123456
#spring.datasource.driver-class-name=com.p6spy.engine.spy.P6SpyDriver


spring.datasource.dynamic.primary=master
spring.datasource.dynamic.datasource.master.username=root
spring.datasource.dynamic.datasource.master.password=123456
spring.datasource.dynamic.datasource.master.driverClassName=com.p6spy.engine.spy.P6SpyDriver
spring.datasource.dynamic.datasource.master.url=jdbc:p6spy:mysql://120.78.181.48:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true

spring.datasource.dynamic.datasource.slave.username=root
spring.datasource.dynamic.datasource.slave.password=123456
spring.datasource.dynamic.datasource.slave.driverClassName=com.p6spy.engine.spy.P6SpyDriver
spring.datasource.dynamic.datasource.slave.url=jdbc:p6spy:mysql://127.0.0.1:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true

上面配置了两个数据源,pom中引入的包支持用dynamic格式,若是想继续加数据源,按照格式配置slave; 同时引用了p6spy的sql日志打印,需要添加spy.properties 文件 如下

module.log=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory
# 自定义日志打印
logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger
#日志输出到控制台
appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger
# 使用日志系统记录 sql
#appender=com.p6spy.engine.spy.appender.Slf4JLogger
# 设置 p6spy driver 代理
deregisterdrivers=true
# 取消JDBC URL前缀
useprefix=true
# 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset.
excludecategories=info,debug,result,batch,resultset
# 日期格式
dateformat=yyyy-MM-dd HH:mm:ss
# 实际驱动可多个
#driverlist=org.h2.Driver
# 是否开启慢SQL记录
outagedetection=true
# 慢SQL记录标准 2 秒
outagedetectioninterval=2

动态数据源模板; 引用值mybatisplus 官网


spring:
  datasource:
    dynamic:
      primary: master #设置默认的数据源或者数据源组,默认值即为master
      datasource:
        master:
          username: root
          password: 123456
          driver-class-name: com.mysql.jdbc.Driver
          url: jdbc:mysql://xx.xx.xx.xx:3306/dynamic
        slave_1:
          username: root
          password: 123456
          driver-class-name: com.mysql.jdbc.Driver
          url: jdbc:mysql://xx.xx.xx.xx:3307/dynamic
        slave_2:
          username: root
          password: 123456
          driver-class-name: com.mysql.jdbc.Driver
          url: jdbc:mysql://xx.xx.xx.xx:3308/dynamic
       #......省略
       #以上会配置一个默认库master,一个组slave下有两个子库slave_1,slave_2

使用方法:
使用 @DS 切换数据源。
@DS 可以注解在方法上和类上,同时存在方法注解优先于类上注解。

注解在service实现或mapper接口方法上,但强烈不建议同时在service和mapper注解。 (可能会有问题)

常规注解@MapperScan(basePackages=“com.sonhai.springboot.bootmybatis.mapper”) 包扫描
在application入口上加或者在配置类上加都行
本次是在配置类上加,同时添加 分页支持

@Configuration
@MapperScan(basePackages="com.sonhai.springboot.bootmybatis.mapper")
public class MybatisPlusConfig {

    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        // paginationInterceptor.setLimit(你的最大单页限制数量,默认 500 条,小于 0 如 -1 不受限制);
        return paginationInterceptor;
    }

}

业务代码展示
entity

package com.sonhai.springboot.bootmybatis.entity;

import lombok.Data;

/**
 * @Author: hw
 * @Date: 2019/9/24 10:01
 * @Description: TODO
 * @Version: 1.0
 */

@Data
public class Account  {
    private int id ;
    private String name ;
    private double money;

}

controller

package com.sonhai.springboot.bootmybatis.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sonhai.springboot.bootmybatis.entity.Account;
import com.sonhai.springboot.bootmybatis.mapper.AccountMapper;
import com.sonhai.springboot.bootmybatis.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Author: hw
 * @Date: 2019/9/24 11:03
 * @Description: TODO
 * @Version: 1.0
 */
@RestController
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private IAccountService accountService;

    @GetMapping("/list1")
    public List findAll(@RequestParam("pageNo") int pageNo,@RequestParam("pageSize") int pageSize){
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("id",1);
        IPage accountIPage = accountService.selectPageVo(new Page(pageNo, pageSize), 0);
        List records = accountIPage.getRecords();
        System.out.println("总页数:  "+accountIPage.getPages());
        System.out.println("总记录数:  "+accountIPage.getTotal());
        return records;

//        return accountService.selectAll();
    }

    @GetMapping("/list2")
    public List findList(){
        return accountService.selectAll();
    }
}

service

package com.sonhai.springboot.bootmybatis.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sonhai.springboot.bootmybatis.entity.Account;
import com.baomidou.mybatisplus.extension.service.IService;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * 

* 服务类 *

* * @author sonhai * @since 2019-09-24 */ public interface IAccountService extends IService { IPage selectPageVo(Page page, Integer id); List selectAll(); }

serviceimpl

package com.sonhai.springboot.bootmybatis.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sonhai.springboot.bootmybatis.entity.Account;
import com.sonhai.springboot.bootmybatis.mapper.AccountMapper;
import com.sonhai.springboot.bootmybatis.service.IAccountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 

* 服务实现类 *

* * @author sonhai * @since 2019-09-24 */ @Service @DS("slave") public class AccountServiceImpl extends ServiceImpl implements IAccountService { @Autowired private AccountMapper accountMapper; @Override public IPage selectPageVo(Page page, Integer id) { return accountMapper.selectPageVo(page,id); } @DS("master") @Override public List selectAll() { return accountMapper.selectList(null); } }

mapper

package com.sonhai.springboot.bootmybatis.mapper;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sonhai.springboot.bootmybatis.entity.Account;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * @Author: hw
 * @Date: 2019/9/24 10:52
 * @Description: TODO
 * @Version: 1.0
 */
public interface  AccountMapper extends BaseMapper {

    /**
     * 

* 查询 : 根据state状态查询用户列表,分页显示 * 注意!!: 如果入参是有多个,需要加注解指定参数名才能在xml中取值 *

* * @param page 分页对象,xml中可以从里面进行取值,传递参数 Page 即自动分页,必须放在第一位(你可以继承Page实现自己的分页对象) * @param id 状态 * @return 分页对象 */ IPage selectPageVo(Page page, @Param("id") Integer id); }

xml





    
        
        
        
        
    


    


最后附上自动生成代码工具

package com.sonhai.springboot.bootmybatis.util;


import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.FileOutConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @Author: hw
 * @Date: 2019/9/24 11:37
 * @Description: TODO
 * @Version: 1.0
 */
public class CodeGenerator {

    /**
     * 

* 读取控制台内容 *

*/ public static String scanner(String tip) { Scanner scanner = new Scanner(System.in); StringBuilder help = new StringBuilder(); help.append("请输入" + tip + ":"); System.out.println(help.toString()); if (scanner.hasNext()) { String ipt = scanner.next(); if (StringUtils.isNotEmpty(ipt)) { return ipt; } } throw new MybatisPlusException("请输入正确的" + tip + "!"); } public static void main(String[] args) { // 代码生成器 AutoGenerator mpg = new AutoGenerator(); mpg.setTemplateEngine(new FreemarkerTemplateEngine()); // 全局配置 GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); gc.setOutputDir(projectPath + "/boot-mybatis/src/main/java"); gc.setAuthor("sonhai"); gc.setOpen(false); // gc.setSwagger2(true); 实体属性 Swagger2 注解 mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://120.0.0.1:3306/test?useUnicode=true&useSSL=false&characterEncoding=utf8"); // dsc.setSchemaName("public"); dsc.setDriverName("com.mysql.cj.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("123456"); mpg.setDataSource(dsc); // 包配置 PackageConfig pc = new PackageConfig(); pc.setModuleName(scanner("模块名")); pc.setParent("com.sonhai.springboot"); mpg.setPackageInfo(pc); // 自定义配置 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { // to do nothing } }; // 如果模板引擎是 freemarker String templatePath = "/templates/mapper.xml.ftl"; // 如果模板引擎是 velocity // String templatePath = "/templates/mapper.xml.vm"; // 自定义输出配置 List focList = new ArrayList<>(); // 自定义配置会被优先输出 focList.add(new FileOutConfig(templatePath) { @Override public String outputFile(TableInfo tableInfo) { // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!! return projectPath + "/boot-mybatis/src/main/resources/mapper/" + pc.getModuleName() + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; } }); /* cfg.setFileCreate(new IFileCreate() { @Override public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) { // 判断自定义文件夹是否需要创建 checkDir("调用默认方法创建的目录"); return false; } }); */ cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); // 配置模板 TemplateConfig templateConfig = new TemplateConfig(); // 配置自定义输出模板 //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别 // templateConfig.setEntity("templates/entity2.java"); // templateConfig.setService(); // templateConfig.setController(); templateConfig.setXml(null); mpg.setTemplate(templateConfig); // 策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); strategy.setSuperEntityClass("com.sonhai.springboot.bootmybatis.entity"); strategy.setEntityLombokModel(true); strategy.setRestControllerStyle(true); // 公共父类 strategy.setSuperControllerClass("com.sonhai.springboot.bootmybatis.controller"); // 写于父类中的公共字段 strategy.setSuperEntityColumns("id"); strategy.setInclude(scanner("表名,多个英文逗号分割").split(",")); strategy.setControllerMappingHyphenStyle(true); strategy.setTablePrefix(pc.getModuleName() + "_"); mpg.setStrategy(strategy); mpg.setTemplateEngine(new FreemarkerTemplateEngine()); mpg.execute(); } }

你可能感兴趣的:(springboot,mybatisplus)