Basic use of Mybatis Plus in basic development

Mybatis-Plus Mybatis dynamic SQL is automatically injected into mybatis to add, delete, modify and query CRUD operation middleware, reduce your development cycle, optimize the dynamic maintenance of XML entity fields, and provide you with more time to spend with your family in the omni-directional ORM auxiliary layer without invasion.

The following contents are based on mybatis plus version 3.0.1;

See official documents for details:

https://mp.baomidou.com/guide/#%E7%89%B9%E6%80%A7 

 

 

Spring boot 2.0 integrates mybatis plus

  1. jar package required for pom introduction
    1. <!-- mybatisPlus Core library -->
              <dependency>
                  <groupId>com.baomidou</groupId>
                  <artifactId>mybatis-plus-boot-starter</artifactId>
                  <version>3.1.0</version>
              </dependency>
              <dependency>
                  <groupId>com.baomidou</groupId>
                  <artifactId>mybatis-plus-extension</artifactId>
                  <version>3.1.0</version>
              </dependency>
              <!-- mybatis Code auto generator -->
              <dependency>
                  <groupId>com.baomidou</groupId>
                  <artifactId>mybatis-plus-generator</artifactId>
                  <version>3.1.0</version>
              </dependency>
              <!--mybatis-plus Template required to complete project construction, real project does not need to use-->
              <dependency>
                  <groupId>org.freemarker</groupId>
                  <artifactId>freemarker</artifactId>
              </dependency>

       

  2. Configure auto generate tool class
    1. package org.xx.xx.db.util;
      
      import com.baomidou.mybatisplus.core.toolkit.StringPool;
      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.DateType;
      import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
      import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
      
      import java.util.ArrayList;
      import java.util.List;
      
      /**
       * @Description:
       * @Auther: wuxw
       * @Date: 2019/9/30 14:27
       */
      public class CodeGeneratorUtil {
      
          public static void main(String[] args) {
              //Code generator 
              AutoGenerator mpg = new AutoGenerator();
      
              //Global configuration
              GlobalConfig gc = new GlobalConfig();
              String projectPath = System.getProperty("user.dir") + "/litemall-db/";
              gc.setOutputDir(projectPath + "/src/main/java");
              gc.setAuthor("wuxw");
              gc.setServiceName("%sService");//File name generated by custom Service interface
              gc.setOpen(false);
              gc.setBaseResultMap(true);
              gc.setDateType(DateType.ONLY_DATE);
              mpg.setGlobalConfig(gc);
      
              //Data source configuration
              DataSourceConfig dsc = new DataSourceConfig();
              dsc.setUrl("jdbc:mysql://127.0.0.1:3306/litemall?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8");
              dsc.setDriverName("com.mysql.cj.jdbc.Driver");
              dsc.setUsername("root");
              dsc.setPassword("123456");
              mpg.setDataSource(dsc);
      
              //Packet configuration
              PackageConfig pc = new PackageConfig();
              pc.setParent("org.xxx.xxx.db")
                      .setMapper("dao");
              mpg.setPackageInfo(pc);
      
              //Custom configuration
              InjectionConfig cfg = new InjectionConfig() {
                  @Override
                  public void initMap() {
                      //to do nothing
                  }
              };
      
              //Custom output configuration
              List<FileOutConfig> focList = new ArrayList<>();
              //Custom configuration will give priority to output
              focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
                  @Override
                  public String outputFile(TableInfo tableInfo) {
                      // Customize the output file name. If you set the prefix and suffix for Entity, please note that the name of xml will change accordingly!!
                      return projectPath + "/src/main/resources/mappers/"
                              + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
                  }
              });
              cfg.setFileOutConfigList(focList);
              mpg.setCfg(cfg);
      
      
              // Configuration template
              TemplateConfig templateConfig = new TemplateConfig();
      
              // Configure custom output templates
              //Specify the path of the custom template. Be careful not to bring. ftl/.vm. It will be automatically recognized according to the template engine used
              // templateConfig.setEntity("templates/entity2.java");
              // templateConfig.setService();
              // templateConfig.setController();
              templateConfig.setXml(null);
              mpg.setTemplate(templateConfig);
      
      
              //Configuration policy
              StrategyConfig strategy = new StrategyConfig();
              strategy.setNaming(NamingStrategy.underline_to_camel);
              strategy.setColumnNaming(NamingStrategy.underline_to_camel);
              //strategy.setSuperControllerClass("com.example.demo.model.BaseEntity");
              strategy.setEntityLombokModel(false);//Default is false
              //strategy.setRestControllerStyle(true);
              //Public parent class
              //strategy.setSuperControllerClass("com.example.demo.controller.BaseController");
              // Public fields written in the parent class
              //strategy.setSuperEntityColumns("id");
              strategy.setInclude("tb_forum_replay"); // Generate a single table only
              strategy.setControllerMappingHyphenStyle(true);
              strategy.setTablePrefix("tb_");
              mpg.setStrategy(strategy);
              mpg.setTemplateEngine(new FreemarkerTemplateEngine());
              mpg.execute();
              System.out.println(" --------------------------Auto generation complete------------------------");
          }
      }

       

  3. Actual development
    1. 
      @Api(tags = "Forum Homepage")
      @RestController
      @RequestMapping("/admin/forum/")
      @Validated
      public class AdminForumController {
      
      }
      
      
      @Service
      public class ForumServiceImpl extends ServiceImpl<ForumMapper, Forum> implements ForumService {
      
      
      }
      
      
      @Mapper
      public interface ForumMapper extends BaseMapper<Forum> {
      
      
      }
      
      @Data
      @TableName("tb_forum")
      public class Forum implements Serializable {
      
      
      }

       

 

Actual development and use

 

Select

First selectCount

QueryWrapper qw = new QueryWrapper();
qw.eq("user_id",userId);
qw.eq("readed",0);
baseMapper.selectCount(qw);

Equate to

select count(*) from tb where use_id = #{userId} and readed =0 

The second selectOne

QueryWrapper qw = new QueryWrapper();
qw.eq("user_id",userId);
qw.eq("readed",0);
qw.last("limit 1");
baseMapper.selectOne(qw);

Equate to

select count(*) from tb where use_id = #{userId} and readed =0 limit 1

update

First set

UpdateWrapper uw = new UpdateWrapper();
uw.eq("user_id",userId);
uw.eq("id",id);
Forum f = new Forum();
f.setDeleted(1);
return forumMapper.update(f,uw) > 0;

Equate to

update forum set delete =1 where user_id = #{userId} and id = #{id}

The second kind of insql

UpdateWrapper uw = new UpdateWrapper();
String[] idsStr =new String["1","2","3"];
String id =  StringUtils.strip(idsStr.toString(),"[]");
uw.inSql("id",id);
Forum f = new Forum();
f.setDeleted(1);
return forumMapper.update(f,uw) > 0;

Equate to

update forum set deleted = 1 where id in ( 1 , 2 ,3)

 

Where is madam? Let's see the official documents

Conditional constructor

All kinds of sql semantics let you fly with mybatisPlus

allEq

eq

ne

...

The most important thing is

MybatisX rapid development plug-in

  • Java and XML callback jump
  • Mapper method generates XML automatically

Tags: Programming Mybatis xml Java SQL

Posted on Tue, 05 Nov 2019 08:07:04 -0800 by Thikho