美文网首页
SpringBoot集成MyBatis-Plus框架

SpringBoot集成MyBatis-Plus框架

作者: 孤独时代的飞 | 来源:发表于2022-08-10 11:05 被阅读0次

1、POM

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.7</version>
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <artifactId>shop-product-server</artifactId>
    <version>1.0.0</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>fr.opensagres.xdocreport</groupId>
            <artifactId>fr.opensagres.xdocreport.template.freemarker</artifactId>
            <version>2.0.2</version>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.19</version>
        </dependency>
    </dependencies>
</project>

2、配置 application.yml

server:
  port: 8081
spring:
  application:
    name: product-service
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://00.00.00.00:3306/shop-product?characterEncoding=utf-8&useSSL=false&autoReconnect=true&rewriteBatchedStatements=true&nullCatalogMeansCurrent=true&allowMultiQueries=true&serverTimezone=GMT%2B8
    username: root
    password: root
    hikari:
      max-lifetime: 1800000
      connection-timeout: 5000
      idle-timeout: 3600000
      maximum-pool-size: 12
      minimum-idle: 4
      connection-test-query: /**ping*/

mybatis-plus:
  configuration:
    #显示SQL输出
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  global-config:
    db-config:
      logic-delete-field: delete_flag
      id-type: auto
  mapper-locations: classpath:/mapper/*.xml

3、配置类 MybatisPlusConfig.class

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Slf4j
@Component
public class MybatisPlusConfig implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        Date date = new Date();
        this.setFieldValByName("createDate", date, metaObject);
        this.setFieldValByName("updateDate", date, metaObject);
        this.setFieldValByName("deleteFlag", false, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Date date = new Date();
        this.setFieldValByName("updateDate", date, metaObject);
    }
}

4、BaseEntity.class

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableLogic;
import lombok.Getter;
import lombok.Setter;

import java.util.Date;

@Getter
@Setter
public class BaseEntity {

    @TableField(fill = FieldFill.INSERT)
    private Date createDate;


    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date updateDate;

    @TableLogic
    @TableField(fill = FieldFill.INSERT)
    private Boolean deleteFlag;
}

5、代码生成器

import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.shop.product.common.BaseEntity;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author LongFei
 */
public class CodeGenerator {

    public static void main(String[] args) {

        FastAutoGenerator.create("jdbc:mysql://00.00.00.00:3306/shop-product", "root", "root")
                // 全局配置
                .globalConfig((builder) ->
                        builder.author("LongFei") //作者
                                .outputDir("D:\\demo_springcloud\\springcloud-alibaba-demo\\shop-product-server\\src\\main\\java")
                                // .enableSwagger() // 开启 swagger 模式
                                .disableOpenDir()//禁止打开输出目录
                                .fileOverride()// 覆盖已生成文件
                )
                // 包配置
                .packageConfig((builder) ->
                        builder.parent("com.shop.product")
                                // 设置mapperXml生成路径
                                .pathInfo(Collections.singletonMap(OutputFile.xml, "D:\\demo_springcloud\\springcloud-alibaba-demo\\shop-product-server\\src\\main\\resources\\mapper"))
                )
                // 策略配置
                .strategyConfig((scanner, builder) ->
                        builder.addInclude(getTables(scanner.apply("请输入表名,多个英文逗号分隔?所有输入 all")))
                                .addTablePrefix("t_", "c_")//忽略表前缀
                                .mapperBuilder().enableBaseResultMap()//启用 BaseResultMap 生成
                                .controllerBuilder().enableRestStyle().enableHyphenStyle()
                                .entityBuilder().enableLombok().superClass(BaseEntity.class)
                                .addSuperEntityColumns("delete_flag", "create_date", "update_date")
                                .build()
                )
                .templateEngine(new FreemarkerTemplateEngine())
                .execute();
    }

    // 处理 all 情况
    protected static List<String> getTables(String tables) {
        return "all".equals(tables) ? Collections.emptyList() : Arrays.asList(tables.split(","));
    }

}

配置可见:

代码生成器配置新 | MyBatis-Plus (baomidou.com)

6、sql脚本

CREATE TABLE `t_product` (
  `id` bigint(12) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `price` decimal(10,2) DEFAULT NULL,
  `stock` int(255) DEFAULT NULL,
  `create_date` datetime DEFAULT NULL,
  `update_date` datetime DEFAULT NULL,
  `delete_flag` bit(1) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=latin1;

7、使用代码生成器,输入表名生成代码

8、测试controller

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shop.product.entity.Product;
import com.shop.product.service.IProductService;
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.RestController;

import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private IProductService productService;

    @GetMapping("/add")
    public String add() {
        Product product = new Product();
        product.setName("11");
        product.setPrice(BigDecimal.ONE);
        product.setStock(1);
        productService.save(product);
        return "success";
    }

    @GetMapping("/list")
    public String list() {
        IPage<Product> page = new Page<>(1,10);
        productService.page(page);
        List<Product> records = page.getRecords();
        return JSONUtil.toJsonStr(records);
    }

}

9、包目录

image.png

10、参考

简介 | MyBatis-Plus (baomidou.com)

相关文章

网友评论

      本文标题:SpringBoot集成MyBatis-Plus框架

      本文链接:https://www.haomeiwen.com/subject/hoaowrtx.html