springboot整合MybatisPlus

2023-12-25 18:50:25 浏览数 (2)

文章来源

最近遇到了项目需要用到MybatisPlus,所以想自己整理一篇demo,自己当笔记本查阅

源码下载

亲测有效

https://github.com/cbeann/Demooo/tree/master/springboot-mybatisplus-demo

实践

pom

代码语言:javascript复制
 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.20</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.2</version>
        </dependency>
        <!-- mybatis plus 代码生成器依赖 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.3.2</version>
        </dependency>
        <!-- 代码生成器模板 -->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
            <scope>provided</scope>
        </dependency>

MP代码生成器

自动生成代码

代码语言:javascript复制
package com.example.demo;



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

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;

// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
public class CodeGenerator {

    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    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();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = "/Users/cbeann/work/IdeaWorkspace/Demooo/springboot-mybatisplus-demo";
        gc.setOutputDir(projectPath   "/src/main/java");
        gc.setAuthor("cbeann");
        gc.setOpen(false);
        // service 命名方式
        gc.setServiceName("%sService");
        // service impl 命名方式
        gc.setServiceImplName("%sServiceImpl");
        // 自定义文件命名,注意 %s 会自动填充表实体属性!
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        gc.setFileOverride(true);
        gc.setActiveRecord(true);
        // XML 二级缓存
        gc.setEnableCache(false);
        // XML ResultMap
        gc.setBaseResultMap(true);
        // XML columList
        gc.setBaseColumnList(false);
        // gc.setSwagger2(true); 实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useSSL=false&characterEncoding=utf-8");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("root");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        //pc.setModuleName(scanner("模块名"));
        pc.setParent("com.example.demo");
        pc.setEntity("entity");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        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<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                String moduleName = pc.getModuleName()==null?"":pc.getModuleName();
                return projectPath   "/src/main/resources/mapper/"   moduleName
                          "/"   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("cn.com.bluemoon.demo.entity");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        // 公共父类
        //strategy.setSuperControllerClass("cn.com.bluemoon.demo.controller");
        // 写于父类中的公共字段
        //strategy.setSuperEntityColumns("id");
        strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName()   "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

}

整合boot

config:分页
代码语言:javascript复制
package com.example.demo.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;


@Configuration
@ConditionalOnClass(value = {PaginationInterceptor.class})
public class MybatisPlusConfig {
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        return paginationInterceptor;
    }
}
yml
代码语言:javascript复制
spring:
  #数据库配置
  datasource:
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&useSSL=false&characterEncoding=utf-8
    username: root
    password: root
    # 使用druid数据源
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
测试mapper
代码语言:javascript复制
package com.example.demo;

import java.util.List;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

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.example.demo.entity.Student;
import com.example.demo.mapper.StudentMapper;

@SpringBootTest
class MapperTests {


    @Autowired
    private StudentMapper studentMapper;






    @Test
    void add() {

        Student student = new Student();
        student.setId(1);//无效
        student.setName("1");
        student.setAge(1);
        student.setSex(1);
        studentMapper.insert(student);


    }

    @Test
    void del() {

        int i = studentMapper.deleteById(4);
        System.out.println(i);


    }

    @Test
    void update() {

        //不设置的不改为空
        Student student = new Student();
        student.setId(1);
        student.setName("1");
        student.setAge(1);
        student.setSex(1);
        studentMapper.updateById(student);


    }

    @Test
    void select() {


        Student student = studentMapper.selectById(1);
        System.out.println(student);


    }

    @Test
    void selectCondition() {

        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("age", "1");

        List<Student> students = studentMapper.selectList(queryWrapper);
        System.out.println(students);



     /*   IPage<Student> userPage = new Page<>(2, 2);//参数一是当前页,参数二是每页个数

        IPage<Student> studentIPage = studentMapper.selectPage(userPage, null);

        List<Student> records = studentIPage.getRecords();

        System.out.println(records);*/


    }

    @Test
    void selectConditionPage() {

        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("age", "1");


        IPage<Student> userPage = new Page<>(2, 3);//参数一是当前页,参数二是每页个数

        IPage<Student> studentIPage = studentMapper.selectPage(userPage, null);

        List<Student> records = studentIPage.getRecords();

        System.out.println("记录:"   records);
        System.out.println("当前页数:"   userPage.getCurrent());
        System.out.println("总页数:"   userPage.getPages());
        System.out.println("没夜多少:"   userPage.getSize());
        System.out.println("一共多少记录:"   userPage.getTotal());


    }


}
测试service
代码语言:javascript复制
package com.example.demo;

import java.util.List;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

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.example.demo.entity.Student;
import com.example.demo.mapper.StudentMapper;

@SpringBootTest
class MapperTests {


    @Autowired
    private StudentMapper studentMapper;






    @Test
    void add() {

        Student student = new Student();
        student.setId(1);//无效
        student.setName("1");
        student.setAge(1);
        student.setSex(1);
        studentMapper.insert(student);


    }

    @Test
    void del() {

        int i = studentMapper.deleteById(4);
        System.out.println(i);


    }

    @Test
    void update() {

        //不设置的不改为空
        Student student = new Student();
        student.setId(1);
        student.setName("1");
        student.setAge(1);
        student.setSex(1);
        studentMapper.updateById(student);


    }

    @Test
    void select() {


        Student student = studentMapper.selectById(1);
        System.out.println(student);


    }

    @Test
    void selectCondition() {

        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("age", "1");

        List<Student> students = studentMapper.selectList(queryWrapper);
        System.out.println(students);



     /*   IPage<Student> userPage = new Page<>(2, 2);//参数一是当前页,参数二是每页个数

        IPage<Student> studentIPage = studentMapper.selectPage(userPage, null);

        List<Student> records = studentIPage.getRecords();

        System.out.println(records);*/


    }

    @Test
    void selectConditionPage() {

        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("age", "1");


        IPage<Student> userPage = new Page<>(2, 3);//参数一是当前页,参数二是每页个数

        IPage<Student> studentIPage = studentMapper.selectPage(userPage, null);

        List<Student> records = studentIPage.getRecords();

        System.out.println("记录:"   records);
        System.out.println("当前页数:"   userPage.getCurrent());
        System.out.println("总页数:"   userPage.getPages());
        System.out.println("没夜多少:"   userPage.getSize());
        System.out.println("一共多少记录:"   userPage.getTotal());


    }


}

参考

SpringBoot整合MyBatis-Plus详细使用方法 - 简书

MyBatis-Plus代码自动生成工具_CBeann的博客-CSDN博客_mybatisplus代码生成工具

MyBatis-Plus整合Spring Demo_CBeann的博客-CSDN博客_mybatis-plus spring

0 人点赞