欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot整合MybatisPlus+单表CRUD(详解)

程序员文章站 2022-07-06 08:41:20
1 创建测试表SET FOREIGN_KEY_CHECKS=0;-- ------------------------------ Table structure for user-- ----------------------------DROP TABLE IF EXISTS `user`;CREATE TABLE `user` ( `id` bigint(20) NOT NULL, `username` varchar(20) NOT NULL, `password` va...

1 创建测试表

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` bigint(20) NOT NULL,
  `username` varchar(20) NOT NULL,
  `password` varchar(20) NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `email` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2 创建SpringBoot项目

创建时用阿里镜像服务:https://start.aliyun.com 快速创建项目
SpringBoot整合MybatisPlus+单表CRUD(详解)
SpringBoot整合MybatisPlus+单表CRUD(详解)

选择Lombok插件 web模块和mySql驱动
SpringBoot整合MybatisPlus+单表CRUD(详解)
SpringBoot整合MybatisPlus+单表CRUD(详解)

3 配置

pom.xml

 		<!--mp-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
        <!--mp代码生成器-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.2.0</version>
        </dependency>

application.yml
说明
mapper-locations指的是Mapper的路径
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl指的是执行的sql语句打印到控制台
注意:数据源使用自己的

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mp?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai
    username: 
    password: 
mybatis-plus:
  mapper-locations: classpath*:/mapper/**Mapper.xml
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
server:
  port: 8082

MybatisPlusConfig
配置mapper路径和分页

package com.yxx.testmp.config;

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@MapperScan("com.yxx.testmp.mapper")
public class MybatisPlusConfig {

    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        return paginationInterceptor;
    }
}

代码生成器 在启动类TestmpApplication同级目录下创建
注意:数据源使用自己的

package com.yxx.testmp;

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.*;
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;

// 演示例子,执行 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 = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
//        gc.setOutputDir("D:\\test");
        gc.setAuthor("yxx");
        gc.setOpen(false);
        gc.setSwagger2(true); //实体属性 Swagger2 注解
        gc.setServiceName("%sService");
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/mp?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("");
        dsc.setPassword("");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(null);
        pc.setParent("com.yxx.testmp");
        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 的名称会跟着发生变化!!
                return projectPath + "/src/main/resources/mapper/"
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });

        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}

3 启动逆向工程创建项目基础框架

运行CodeGenerator的main方法即可
SpringBoot整合MybatisPlus+单表CRUD(详解)
自动生成了包结构等等
SpringBoot整合MybatisPlus+单表CRUD(详解)

4 单表CRUD

/*
  * 增加
  * */
  @Test
  public void testInsert(){
    User user = new User();
    user.setUsername("lal");
    user.setPassword("lal");
    user.setName("lal");
    user.setAge(15);
    user.setEmail("lalal");
    int insert = userMapper.insert(user);//insert表示受影响的行数 不是自增的id
    long id=user.getId(); //执行成功之后会回传一个自增的id
  }

更新

/*更新
  * */
  @Test
  public void testUpdateById(){
    User user = new User();
    user.setId(1l);
    user.setUsername("1号");
    int update = userMapper.updateById(user);
  }
  @Test
  public void testUpdate(){
    //使用QueryWrapper更新
    User user = new User();
    user.setUsername("2号");
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("username","lal");
    int update1 = userMapper.update(user, queryWrapper);

    //使用QueryWrapper更新
    UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
    updateWrapper.set("age",16).eq("age",1);
    int update2 = userMapper.update(null, updateWrapper);
  }

删除

/*删除
  * */
  @Test
  public void testDeleteById(){
    userMapper.deleteById(3l);
  }
  @Test
  public void testDeleteByMap(){
    HashMap<String, Object> map = new HashMap<>();
    map.put("username","lal");
    map.put("password","lal");
    userMapper.deleteByMap(map);
  }

  @Test
  public void testDelete(){
    //方法1
    /*QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("username","lal").eq("password","lal");*/
    //方法2
    User user = new User();
    user.setUsername("lal");
    user.setPassword("lal");
    QueryWrapper<User> queryWrapper = new QueryWrapper<>(user);
    userMapper.delete(queryWrapper);
  }
  @Test
  public void testDeleteBatchIds(){
    userMapper.deleteBatchIds(Arrays.asList(1l,2l));
  }

查询

 /*查询
  * */
  @Test
  public void testSelectById(){
    User user = userMapper.selectById(1l);
  }
  @Test
  public void testSelectBatchIds(){
    userMapper.selectBatchIds(Arrays.asList(1l,2l));
  }

  @Test
  public void testSelectOne(){
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("username","1号");
    User user = userMapper.selectOne(queryWrapper);
  }

  @Test
  public void testSelectCount(){
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.gt("age","10");
    Integer integer = userMapper.selectCount(queryWrapper);
  }

  @Test
  public void testSelectList(){
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.like("username","号");
    List<User> users = userMapper.selectList(queryWrapper);
    System.out.println(users);
  }

  @Test
  public void testSelectPage(){
    Page<User> userPage = new Page<>(1,5);
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.like("username","号");
    IPage<User> userIPage = userMapper.selectPage(userPage,queryWrapper);
    System.out.println("总条数"+userIPage.getTotal());
    System.out.println("总页数"+userIPage.getPages());
    System.out.println("当前页"+userIPage.getCurrent());
    List<User> records = userIPage.getRecords();
  }

5 一些小细节

在实体类的主键上加上@TableId(type=IdType.AUTO)使得程序逻辑和数据库逻辑一致
SpringBoot整合MybatisPlus+单表CRUD(详解)
mapper注入爆红的话给Mapper加上@Repository注解就行了(这不是必须的 因为我们在配置文件中已经制定了Mapper的路径 这里的爆红是ide的问题并不影响的 )
SpringBoot整合MybatisPlus+单表CRUD(详解)
SpringBoot整合MybatisPlus+单表CRUD(详解)

本文地址:https://blog.csdn.net/qq_44173974/article/details/107351933

相关标签: java SpringBoot