This article is reproduced at:www.cnblogs.com/gaogushenli…

A, configuration,

pom

<! B: Needless to say. <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <! --mp dependency --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> The < version > 3.4.0 < / version > < / dependency > <! <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> The < version > 3.4.0 < / version > < / dependency > <! Freemarker </groupId> <artifactId> Freemarker </artifactId> The < version > 2.3.30 < / version > < / dependency >Copy the code

Yml configures the database

Mybatis -plus: mapper-locations: classpath:mapper/**/* mapper. XML type-aliases-package: mybatis-plus: mapper-locations: classpath:mapper/**/* Domain global-config: db-config: # logic-not-delete-value: logic-not-delete-value: Delete field is 1 0 # configuration logic is deleted logic - delete - value: 1 # print SQL statements configuration: log - impl: org. Apache. The ibatis. Logging. Stdout. StdOutImplCopy the code

Code generators

Generation effect

Configuration class, run directly

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException; 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.NamingStrategy; import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.List; import java.util.Scanner; // A sample, Public class CodeGenerator {/** * <p> * </p> */ 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)) { return ipt; }} throw new MybatisPlusException(" please enter the correct "+ 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.setAuthor("jobob"); gc.setOpen(false); // gc.setSwagger2(true); Swagger2 entity attribute mpg.setGlobalConfig(GC); // DataSourceConfig DSC = new DataSourceConfig(); DSC. SetUrl (" JDBC: mysql: / / localhost: 3306 / database name? useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&allowMultiQueries=true"); // dsc.setSchemaName("public"); dsc.setDriverName("com.mysql.jdbc.Driver"); Dsc.setusername (" username "); DSC. SetPassword (" password "); mpg.setDataSource(dsc); PackageConfig PC = new PackageConfig(); Pc.setmodulename (scanner(" module name ")); pc.setParent("com.lrk.gzmhostsystem"); mpg.setPackageInfo(pc); InjectionConfig CFG = new ectionConfig() {@override public void initMap() {// to do nothing}}; / / if the template engine is a freemarker String templatePath = "/ templates/mapper. XML. FTL"; // String templatePath = "/templates/mapper.xml.vm"; List<FileOutConfig> focList = new ArrayList<>(); 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/" + pc.getModuleName() + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; }}); /* cfg.setFileCreate(new IFileCreate() { @Override public boolean isCreate(ConfigBuilder configBuilder, FileType FileType, String filePath) {// Check whether the custom folder needs to create checkDir(" call the default directory created, custom directory used "); If (fileType == filetype.mapper) {if (fileType == filetype.mapper) {return false! new File(filePath).exists(); } // allow template files to be generated. }}); */ cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); // TemplateConfig TemplateConfig = new TemplateConfig(); // Configure a custom output template. // Specify a custom template path without. FTL /.vm, which is automatically identified as "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 (" your parent entity, there is no need not set!" ); strategy.setEntityLombokModel(true); strategy.setRestControllerStyle(true); / / public/parent/strategy setSuperControllerClass (" your parent controller, no need not set!" ); / / write in public field in the parent class. / / the strategy setSuperEntityColumns (" id "); Strategy.setinclude (scanner(" table name, multiple English comma split ").split(",")); strategy.setControllerMappingHyphenStyle(true); // strategy.setTablePrefix(pc.getModuleName() + "_"); // Ignore the database table prefix strategy.settablePrefix (" prefix _"); mpg.setStrategy(strategy); mpg.setTemplateEngine(new FreemarkerTemplateEngine()); mpg.execute(); }}Copy the code

Third, the CRUD

@Autowired private IProjectService projectService; / / check in below page position / / add or modify a Boolean flag = projectService. SaveOrUpdate (record); //boolean flag = projectService.saveOrUpdateBatch(Arrays.asList(record)); Batch operations / / delete a Boolean flag. = projectService removeById (record) getId ());Copy the code

4. Paging plug-ins

Website case

/ / Spring boot way @ Configuration @ MapperScan (" com. Baomidou. Cloud. Service. * mapper * ") public class MybatisPlusConfig { @Bean public PaginationInterceptor paginationInterceptor() { PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); / / set the request page after page is greater than the maximum operation, true transferred back to the home page, the default false false continue to request / / paginationInterceptor setOverflow (false); / / set the biggest single page limit an amount, the default 500-1 is not restricted. / / paginationInterceptor setLimit (500); / / open the count of the join optimization, only part of the left join paginationInterceptor. SetCountSqlParser (new JsqlParserCountOptimize (true)); return paginationInterceptor; }}Copy the code

Then it turns out that the PaginationInterceptor is no longer supported. Setusedexecutor is only supported temporarily and will be removed in the next release. Well, we’ll see. We’ll be looking at multiple tables, and we won’t necessarily be using the MP paging plug-in on a large scale

import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer; import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; //Spring boot @configuration @mapperscan (" com.lrk.gzMHostSystem.*.mapper*") public class MybatisPlusConfig {/* Old version Configuration @Bean public PaginationInterceptor paginationInterceptor(){ return new PaginationInterceptor(); MybatisConfiguration#useDeprecatedExecutor = false to avoid caching problems */ @bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return interceptor; } @Bean public ConfigurationCustomizer configurationCustomizer() { return configuration -> configuration.setUseDeprecatedExecutor(false); }}Copy the code

Using the Paging plug-in

QueryWrapper<Project> queryWrapper = new QueryWrapper<>(); queryWrapper.like(StringUtils.isNotEmpty(record.getProjectNumber()),"project_number", record.getProjectNumber()); queryWrapper.orderByDesc("id"); // Page<Project> Page = new Page<>(pageNumber, pageSize); IPage<Project> iPage = projectService.page(page, queryWrapper); Println (" current page: "+ iPage.getCurrent()); System.out.println(" number per page: "+ iPage.getsize ()); System.out.println(" iPage.getTotal() "); System.out.println(" total pages: "+ iPage.getPages()); List<Project> employeeList = iPage.getRecords(); For (Project employee: employeeList) {system.out.println (employee); for (Project employee: employeeList) {system.out.println (employee); }Copy the code

5. Logical deletion

Step 1: Configure application.yml

mybatis-plus: global-config: db-config: logic-delete-field: Flag # Logic-delete-value: 1 # Logic-not -delete-value: 0 # Logically undeleted value (default 0)Copy the code

Step 2: Annotate the @TABLelogic on the entity class field

@TableLogic
private Integer deleted;
Copy the code

Automatic insert create time Modify time is automatic fill function

Set the creation time and update time of the property in the entity class, and add the @tableField annotation to the property

/** * createTime */ @tablefield (fill = FieldFill.INSERT) private LocalDateTime createTime; / / @tableField (fill = FieldFill.INSERT_UPDATE) private LocalDateTime updateTime;Copy the code

The @tablefield annotation fill explains this in detail

Public enum FieldFill {/** * DEFAULT not to handle */ DEFAULT, /** * INSERT, /** * UPDATE, /** * insert and update the fill field */ INSERT_UPDATE}Copy the code

Add configuration files: Write a processor Handler to automate the population

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; import org.apache.ibatis.reflection.MetaObject; import org.springframework.stereotype.Component; import java.time.LocalDateTime; import java.util.Date; /** * @program: our-task * @description: Automatically populate the creation time and update time of each database record * @author: water76016 * @create: 2020-11-24 10:53 **/ @component public class MyMetaObjectHandler implements MetaObjectHandler {/** * implements MetaObjectHandler metaObject */ @Override public void insertFill(MetaObject metaObject) { this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now()); @param metaObject */ @override public void updateFill(metaObject metaObject) { this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); // Version 3.3.0(recommended)}}Copy the code

Note: The filling principle is to set the value of the entity property directly!! MetaObjectHandler provides a default method that does not overwrite the property if it has a value and does not populate it if the value is null The field must declare the TableField annotation, and the property fill selects the corresponding policy. This declaration tells Mybatis-Plus that it needs to reserve the injection of SQL fields to populate the processor MyMetaObjectHandler in Spring Boot To differentiate between the annotation FieldFill. XXX and the field name and field type, you must use strictInsertFill or strictUpdateFill of the parent class There is no need to distinguish between the fillStrategy methods that can use the parent class

7. About the time Date, the back end of the format should be consistent with the front end

@dateTimeFormat (pattern=" YYYY-MM-DD ") @jsonformat (pattern=" YYYY-MM-DD ") private Date startTime; /** * endTime */ @datetimeformat (pattern=" yyyy-mm-dd ") @jsonformat (pattern=" yyyy-mm-dd ") private Date endTime;Copy the code

Data is transferred back end in string year month day format

<div class="form-group"> <label for="startTime"> startTime </label> <input type="date" class="form-control" id="startTime" Name ="startTime"> </div> <div class="form-group"> <label for="endTime"> endTime </label> <input type="date" class="form-control" id="endTime" name="endTime"> </div>Copy the code

Attach the frequently used JS utility class (echo according to the input name data)

Date.prototype.format = function(FMT) {var o = {"M+" : this.getMonth()+1, "d+" : this.getmonth (), "h+" : this.getHours()%12 == 0 ? 12: enclosing getHours () % 12, / / hour "H +" : this. GetHours (), / / hour "m +" : this. GetMinutes (), / / min "s +" : Enclosing getSeconds (), / / SEC "q +" : Math. The floor ((enclosing getMonth () + 3) / 3), / / quarter "S" : this. GetMilliseconds () / / ms}; if(/(y+)/.test(fmt)) fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); for(var k in o) if(new RegExp("("+ k +")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length))); return fmt; } function setFormJsonData(obj) { var key, value, tagName, type, arr, clas; for (x in obj) { key = x; value = obj[x]; $("[name='" + key + "'],[name='" + key + "[]']").each(function () { tagName = $(this)[0].tagName; type = $(this).attr('type'); clas = $(this).attr('class'); if (clas ! = undefined && clas.indexOf("selectpicker") ! = -1) { return; } if (tagName == 'INPUT') { if (type == 'radio') { $(this).attr('checked', $(this).val() == value); } else if (type == 'checkbox') { arr = value.split(','); for (var i = 0; i < arr.length; i++) { if ($(this).val() == arr[i]) { $(this).attr('checked', true); break; } } } else if (type == 'date') { $(this).val(new Date(value).format("yyyy-MM-dd")); } else { $(this).val(value); } } else if (tagName == 'SELECT' || tagName == 'TEXTAREA') { $(this).val(value); }}); }} <! --> new Date(value). Format (" YYYY-MM-DD "); setFormJsonData(row);Copy the code

Eight, summary

  • Official documentation has its own golden house, and in-depth study of documentation is a good way for every developer to go

  • Official website: baomidou.com/