SpringBoot integrates MybatisPlus to generate code and operations

theme: juejin
highlight: SpringBoot + MybatisPlus

Introduction to the

MyBatis-Plus (Opens New Window) (MP) is a new enhancement tool for MyBatis (Opens New Window), which is designed to simplify development and improve efficiency.

features

· Non-intrusion: only enhancement without change, introduction of it will not affect the existing project, as smooth as silk
· Low loss: Basic CURD will be automatically injected upon startup, with basically lossless performance and direct object-oriented operation
· Powerful CRUD operations: built-in universal Mapper and universal Service, most CRUD operations of a single table can be realized only through a small amount of configuration, and there is a powerful conditional constructor to meet all kinds of use requirements
· Support Lambda form call: through Lambda expressions, it is convenient to write various query conditions without worrying about field errors
· Support automatic generation of primary keys: support up to 4 primary key strategies (including distributed unique ID generator – Sequence), can be configured freely, perfect solution to the primary key problem
· Support ActiveRecord mode: Support ActiveRecord form calls, entity classes only need to inherit from Model classes to perform powerful CRUD operations
· Support custom global universal operation: support Write once (use anywhere) global universal method injection
· Built-in code generator: Mapper, Model, Service, Controller layer code can be quickly generated by code or Maven plug-in, support template engine, more customized configurations for you to use
· Built-in paging plug-in: Based on MyBatis physical paging, developers do not need to care about specific operations. After configuring the plug-in, write paging is equivalent to ordinary List query
· Paging plug-in supports a variety of databases: MySQL, MariaDB, Oracle, DB2, H2, HSQL, SQLite, Postgre, SQLServer and other databases
· Built-in performance analysis plug-in: it can output Sql statements and their execution time. It is recommended to enable this function during development and testing to quickly find out slow queries
· Built-in global interception plug-in: provides intelligent analysis and blocking of delete and UPDATE operations of the entire table, and can also define interception rules to prevent misoperations

Support database

Any database that can cruD with Mybatis and supports standard SQL
Using aMyBatis – Plus website

I. Create a project

1. Create a springBoot project using Idea or go to thewebsitedownload

Spring Web, MySQL Driver, Lombok… (Additional dependencies can be added as needed)

Spring Boot Version In the figure above, you can select the version of Springboot you want (download it from the official website and ignore it).

Mybatis_Plus reference dependency

1. Pom introduces dependencies
<! -- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter --><dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>${mybatisplus.version}</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>${mybatisplus.version}</version> </dependency> <! Freemarker </groupId> <artifactId>freemarker</artifactId> <version>2.330.</version> </dependency> <! <dependency> <groupId>org.apache.velocity</groupId> <artifactId> Velocity </artifactId> <version>1.7</version> </dependency> <! --swagger--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>${swagger.version}</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>${swagger.version}</version> </dependency>Copy the code
2. Configuration file
2.1 application. Yml configuration
Spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql: / / 127.0.0.1:3306 /db_name?serverTimezoneMyBatis -plus: mapper-locations: classpath:mapper/**/* mapper. XML # mapping file type-aliases-package: com.mybatisplus. entity # mapping file type-aliases-package: com.mybatisplus. entity org.apache.ibatis.logging.stdout.StdOutImpl global-config: id-type: 0 field-strategy: 2 capital-mode: true refresh-mapper: trueCopy the code

Three. Automatic code generation

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;

public class CodeGenerateUtil {

    /** * Read the console contents */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("Please enter" + tip + ":");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(ipt)) {
                returnipt; }}throw new MybatisPlusException("Please enter the correct one" + tip + "!");
    }
    public static void main(String[] args) {
        // Code generator
        AutoGenerator mpg = new AutoGenerator();

        // Global configuration
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        //gc.setOutputDir("dir:\\xxx");
        // His signature
        gc.setAuthor("code Lin");
        gc.setOpen(false);
        gc.setSwagger2(true); // Entity attribute Swagger2 annotation
        gc.setServiceName("%sService");
        mpg.setGlobalConfig(gc);

        // Data source configuration
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/db_name? useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("password");
        mpg.setDataSource(dsc);

        / / package configuration
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(null);
        pc.setParent("com.mybatisPlus.demo");
        mpg.setPackageInfo(pc);

        // Custom configuration
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap(a) {
                // to do nothing}};// If the template engine is freemarker
        String templatePath = "/templates/mapper.xml.ftl";
        // If the template engine is Velocity
        // String templatePath = "/templates/mapper.xml.vm";

        // Customize the output configuration
        List<FileOutConfig> focList = new ArrayList<>();
        // Custom configurations are printed first
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // Customize the output file name. If your Entity has a prefix or suffix, note that the XML name will change accordingly!!
                return projectPath + "/src/main/resources/mapper/"
                        + "/" + tableInfo.getEntityName() + "Mapper"+ StringPool.DOT_XML; }}); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg);// Configure the template
        TemplateConfig templateConfig = new TemplateConfig();

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

        // Policy configuration
        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("Table name, separated by multiple Commas").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        // Set the table prefix
        strategy.setTablePrefix("tb_"); 
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(newFreemarkerTemplateEngine()); mpg.execute(); }}Copy the code
Output result:

Mybtis_Plus basic operation CRUD

1. The general model
/** * <p> * Student object * </p> **@author code Lin
 * @sinceThe 2021-01-07 * /
@Data
@EqualsAndHashCode(callSuper = false)
@apiModel (value="Student object ", description="")
public class Student implements Serializable {

    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    private String studentName;

    private String email;

    private Integer gender;

    private Integer age;


}
Copy the code
2. General mapper
/** * <p> * Mapper interface * </p> **@author code Lin
 * @sinceThe 2021-01-07 * /
public interface StudentMapper extends BaseMapper<Student> {}Copy the code
3. Mapper – add -insert()
    /** * add */
    @Test
    public void insert(a){
        Student student_new = new Student();
        student_new.setAge(12);
        student_new.setEmail("[email protected]");
        student_new.setGender(3);
        student_new.setStudentName("Cinnamon");
        int insert = studentMapper.insert(student_new);
        if (insert > 0) {
            System.out.println("insert: success"); }}Copy the code
4. Mapper -updateById()
     /** * update */
    @Test
    public void update(a){
        // You can check it first
        // Student student = studentMapper.selectById(7);
        Student student = new Student();
        student.setId(8);
        student.setStudentName(Tathagata Buddha);
        studentMapper.updateById(student);
    }
Copy the code
5. Mapper -deleteById()
Note: Physical deletion
     /** * delete */
    @Test
    public void delete(a){
        Student student = new Student();
        student.setId(8);
        if (studentMapper.deleteById(student.getId()) > 0) {
            System.out.println("delete: success"); }}Copy the code
6. Mapper – Query set -selectList()
6.1 Querying All Data
    @Test
    public void selectList(a) {
        QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
        List<Student> students = studentMapper.selectList(studentQueryWrapper);
        students.forEach(System.out :: println);
        System.out.println("students: QueryWrapper: " + students);
    }
Copy the code
6.2 Fuzzy Query
like() – ‘%%’
likeLeft() – ‘ %’
likeRight() – ‘% ‘
NotLike ().
    /** ** fuzzy query */
    @Test
    public void selectListLike(a) {
        String name = "Enlightenment";
        QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
        studentQueryWrapper.like("student_name",name);
        List<Student> students1 = studentMapper.selectList(studentQueryWrapper);
        System.out.println("Fuzzy query:" + students1);
        System.out.println("Fuzzy query first object:" + students1.get(0));
        System.out.println("Fuzzy query first object name:" + students1.get(0).getStudentName());
    }
Copy the code
6.3 Compound Query
Or (), and (), inSql ()… (Mix it up)
    /**
     * 复合查询
     */
    @Test
    public void selectRecombination(a) {
        QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
        studentQueryWrapper.inSql("gender"."select gender from student where gender = 1").or(st -> st.between("age".22.33));
        List<Student> students1 = studentMapper.selectList(studentQueryWrapper);
        System.out.println("Composite query result:" + students1);
        System.out.println("Length of composite query result:" + students1.size());
    }
Copy the code
6.4 Single Query
    /** * single query */
   @Test
    public void selectByIdTest(a) {
        Student student = studentMapper.selectById(7);
        System.out.println("student = " + student);
    }
Copy the code
7. Service – Simple query and update operation
/** ** <p> **@author code Lin
 * @sinceThe 2021-01-08 * /
@RestController
@RequestMapping("/ancient-poetry")
public class AncientPoetryController {

    @Autowired
    private AncientPoetryService ancientPoetryService;

    @Autowired
    private AncientPoetryMapper ancientPoetryMapper;

    @RequestMapping("/selectList")
    public List<AncientPoetry> selectList(a) {
        return ancientPoetryService.list();
    }

    @RequestMapping("/selectAncientPoetry")
    @ResponseBody
    @apiOperation (value = "ApiOperation ")
    public List<AncientPoetry> selectAncientPoetry(@RequestParam String name, AncientPoetry ancientPoetry) {
        QueryWrapper<AncientPoetry> queryWrapper = new QueryWrapper<>(ancientPoetry);
        queryWrapper.like("chapters", name);
        return ancientPoetryService.list(queryWrapper);
    }

    @RequestMapping("/selectPage")
    @ResponseBody
    @apiOperation (value = "ApiOperation ")
    public Page<AncientPoetry> selectPage(@RequestParam Integer page, @RequestParam Integer pageSize, @RequestParam(required = false) String name, AncientPoetry ancientPoetry) {
        Page<AncientPoetry> ancientPoetryPage = new Page<>();
        ancientPoetryPage.setCurrent(page);
        ancientPoetryPage.setSize(pageSize);
        QueryWrapper<AncientPoetry> ancientPoetryQueryWrapper = new QueryWrapper<>(ancientPoetry);
        if (StringUtils.isNotBlank(name)) {
            ancientPoetryQueryWrapper.like("chapters", name);
        }
        return ancientPoetryService.page(ancientPoetryPage, ancientPoetryQueryWrapper);
    }

    @RequestMapping("/selectChain")
    @ResponseBody
    @apiOperation (value = "")
    public List<AncientPoetry> selectChain(@RequestParam(required = false) String name, AncientPoetry ancientPoetry) {
        QueryChainWrapper<AncientPoetry> ancientPoetryQueryWrapper = new QueryChainWrapper<>(ancientPoetryMapper);
        if (StringUtils.isNotBlank(name)) {
            ancientPoetryQueryWrapper.like("chapters", name);
        }
        return ancientPoetryQueryWrapper.list();
    }

    @RequestMapping("/selectLambdaChain")
    @ResponseBody
    @apiOperation (value = ""); Note: Kotlin is not supported ")
    public List<AncientPoetry> selectLambdaChain(@RequestParam(required = false) String name, AncientPoetry ancientPoetry) {
        LambdaQueryChainWrapper<AncientPoetry> lambdaQueryChainWrapper = new LambdaQueryChainWrapper<>(ancientPoetryMapper);
        if (StringUtils.isNotBlank(name)) {
            // condition Indicates whether the query condition is enabled
            lambdaQueryChainWrapper.like(false, AncientPoetry::getChapters, name);
        }
        return lambdaQueryChainWrapper.list();
    }


    @RequestMapping("/updateChain")
    @ResponseBody
    @apiOperation (value = "ApiOperation ")
    public boolean updateChain(@RequestParam(required = false) String title, AncientPoetry ancientPoetry) {
        UpdateChainWrapper<AncientPoetry> updateChainWrapper = new UpdateChainWrapper<>(ancientPoetryMapper);
        return updateChainWrapper.eq("id", ancientPoetry.getId()).update(ancientPoetry);
    }

    @RequestMapping("/updateLambdaChain")
    @ResponseBody
    @apiOperation (value = "chain update lambda. Note: Kotlin is not supported ")
    public boolean updateLambdaChain(@RequestParam(required = false) String name, AncientPoetry ancientPoetry) {
        LambdaUpdateChainWrapper<AncientPoetry> lambdaUpdateChainWrapper = new LambdaUpdateChainWrapper<>(ancientPoetryMapper);
        lambdaUpdateChainWrapper.eq(AncientPoetry::getId, ancientPoetry.getId());
        returnlambdaUpdateChainWrapper.eq(AncientPoetry::getId, ancientPoetry.getId()).update(ancientPoetry); }}Copy the code
Conclusion:
Mybatis_Plus provides great convenience for development and improves the efficiency of development, just as the official description: based on MyBatis, it only makes enhancements and does not change. It is born to simplify development and improve efficiency.