SpringBoot integrates MyBatis-Plus and MyBatis-Plus code generation tools
Brief introduction:
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.
A detailed example of how to use the built-in method is available on MyBatis-Plus
This article will teach you how to integrate MyBatis-Plus through a few simple steps.
- Add MyBatis-Plus and MyBatis-Plus code generator dependencies to the project’s POM file
<! -- mybatis plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.2. 0</version> </dependency> <! Mybatis -plus-generator --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.2. 0</version>
</dependency>
Copy the code
- Add MyBatis-Plus configuration to yML file
Mapper-locations: classpath:mapper. Use commas or semicolons to separate multiple directories/*.xml # global-config: db-config: global-config: db-config: # primary key type AUTO:" database ID increment "INPUT:" user INPUT ID",ID_WORKER:" globally unique ID (number type unique ID)", UUID:" globally unique ID UUID"; Id-type: auto configuration: # Whether to enable automatic camel naming rule mapping from database column names to Java attribute camel naming similar mapping map-underscore to camel-case: Null; false: null; call-setters-on-nulls: call-setters-on-nulls: True # this configuration will execute SQL print it out, at the time of development or test can use the log - impl: org. Apache. The ibatis. Logging. Stdout. StdOutImplCopy the code
- Add MyBatis-Plus code generator (configure the database and other related configurations, run directly, according to the console prompt input table name enter to generate code)
package com.chentawen.springbootall.config.mybatisplus;
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;
/** * * code generator, use method, run directly; Enter the module name (demo) as prompted by the console, and then the table name *
*/
public class CodeGenerator {
public static final String OUTPUTDIR = "/src/main/java";
public static final String AUTHOR = "ctw";
public static final String DBURL = "JDBC: mysql: / / 127.0.0.1:3306 / authority? allowMultiQueries=true&useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&useSSL=false";
public static final String DBDRIVER = "com.mysql.cj.jdbc.Driver";
public static final String DBUSER = "root";
public static final String DBPASSWORD = "root";
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 + OUTPUTDIR);
gc.setAuthor(AUTHOR);
gc.setOpen(false);
// Whether to overwrite the file
gc.setFileOverride(false);
// Customize the file name
gc.setMapperName("%sMapper");
gc.setServiceName("%sService");
gc.setServiceImplName("%sServiceImpl");
mpg.setGlobalConfig(gc);
// Data source configuration
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl(DBURL);
dsc.setDriverName(DBDRIVER);
dsc.setUsername(DBUSER);
dsc.setPassword(DBPASSWORD);
mpg.setDataSource(dsc);
/ / package configuration
PackageConfig pc = new PackageConfig();
// pc.setModulename (scanner(" module name "));
pc.setParent("com.zhongsheng.educationaladministration");
pc.setEntity("entity");
pc.setXml("mapper");
pc.setService("service");
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/" + pc.getModuleName()
// + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
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);
// Public fields written in the parent class
strategy.setSuperEntityColumns("id");
strategy.setInclude(scanner("The name of the table"));
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
/** * * read the console contents *
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter" + tip + ":");
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
returnipt; }}throw new MybatisPlusException("Please enter the correct one" + tip + "!"); }}Copy the code
Console input table name generation code:
The generated directory structure is as follows:
- Added the MyBatis-Plus paging plug-in configuration class
package com.chentawen.springbootall.config.mybatisplus;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/** * Configure the paging plug-in **@author admin
*/
@Configuration
public class MybatisPlusConfig {
/** ** paging plug-in */
@Bean
public PaginationInterceptor paginationInterceptor(a) {
return newPaginationInterceptor(); }}Copy the code
- Start the class add annotations @ MapperScan (” com. Chentawen. Springbootall. Mapper “) scans all mapper
package com.chentawen.springbootall;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/ * * *@author admin
*/
@SpringBootApplication
@EnableSwagger2
@MapperScan("com.chentawen.springbootall.mapper")
public class SpringBootAllApplication {
public static void main(String[] args) { SpringApplication.run(SpringBootAllApplication.class, args); }}Copy the code
- The above is the whole process of SpringBoot integration MyBatis-Plus, very detailed, and finally attach a grammar map (need a grammar tutorial can comment area, arrange!) :
What doubt can comment area to ask! Thumb up! Please forward! For collection!