The article directories

  • Introduction to the
  • features
  • Frame structure
  • Relying on the integration
    • Rely on
    • configuration
    • coding
    • Begin to use
  • The core function
    • Code generator
      • Add the dependent
      • coding
      • Write the configuration
      • Custom template engine
      • Custom code templates
      • Custom property injection
      • Field Other information query injection
      • Practical summary
  • Commonly used to summarize
    • Multi-table LianZha
    • Enabling Log Printing
      • general
      • Mybatis-Plus
      • Mybatis
    • Update and delete

Similar TkMybatis

Official website address:

baomidou.com/

Introduction to the

MyBatis-Plus (MP for short) is a MyBatis enhancement tool, on the basis of MyBatis only do enhancement do not change, to simplify the development and improve efficiency.

vision

Our vision is to become the best partner of MyBatis, just like 1P and 2P in Contra, the efficiency of gay friends is doubled.

features

  • No intrusion: only enhancements are made, no changes are made, and its introduction will not affect the existing project, as smooth as silk
  • Low loss: Basic CURD will be injected automatically upon startup, with basically no loss in performance and direct object-oriented operation
  • Powerful CRUD operations: built-in universal Mapper, universal Service, only through a small amount of configuration can achieve a single table most CRUD operations, more powerful condition constructor, to meet all types of use requirements
  • Support Lambda form call: through Lambda expressions, it is convenient to write all kinds of query conditions, without worrying about field write errors
  • Support automatic generation of primary keys: support up to four primary key policies (including distributed unique ID generator – Sequence), can be freely configured, perfect solution to the primary key problem
  • Support for ActiveRecord mode: Support for ActiveRecord form calls, entity classes only need to inherit from Model classes to perform powerful CRUD operations
  • Support custom global universal operations: support Write once (use anywhere)
  • Built-in code generator: using code or Maven plug-in can quickly generate Mapper, Model, Service, Controller layer code, support template engine, more than a lot of custom configuration 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 equal to ordinary List query
  • The paging plug-in supports a variety of databases: MySQL, MariaDB, Oracle, DB2, H2, HSQL, SQLite, Postgre, SQLServer, etc
  • Built-in performance analysis plug-in: outputs 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 on all tables, and can customize interception rules to prevent misoperations

Frame structure

Relying on the integration

The new MyBatis-Plus 3.0 version is based on JDK8 and provides lambda form calls, so installing integrated MP3.0 requires JDK8 +

Rely on

Mybatis -plus-boot-starter – mybatis-plus-boot-starter

Introducing Spring Boot Starter parent project:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.4.3</version>
    <relativePath/>
</parent>
Copy the code

Add spring-boot-starter, spring-boot-starter-test, mybatis-plus-boot-starter, h2 dependencies:

Latest Version: Portal

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.4.2</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
</dependencies>
Copy the code

configuration

Add the H2 database configuration to the application.yml configuration file:

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/laker? serverTimezone=GMT%2B8&characterEncoding=utf8&useSSL=false
    driver-class-name: com.mysql.cj.jdbc.Driver
Copy the code

Add the @mapperscan annotation to the Spring Boot Boot class and scan the Mapper folder:

@SpringBootApplication
@MapperScan("com.laker.demo.mapper")
public class Application {
    public static void main(String[] args) { SpringApplication.run(QuickStartApplication.class, args); }}Copy the code

coding

Write the entity class user.java (Lombok simplified code used here)

@Data
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}
Copy the code

Write the Mapper class usermapper.java

public interface UserMapper extends BaseMapper<User> {}Copy the code

Begin to use

Add test classes for functional testing:

@RunWith(SpringRunner.class)
@SpringBootTest
public class SampleTest {
    @Autowired
    private UserMapper userMapper;
    @Test
    public void testSelect(a) {
		List<User> userList = userMapper.selectList(
        			new QueryWrapper<User>()
                		.lambda()
                		.ge(User::getAge, 18));// SELECT * FROM user WHERE age >= 18}}Copy the code

Start demo here is enough, the following are advanced extension features.

The core function

Code generator

AutoGenerator is the code generator of MyBatis-Plus, through which the code of Entity, Mapper, Mapper XML, Service, Controller and other modules can be generated quickly. Greatly improved the development efficiency.

What parameters are available for custom templates? GetObjectMap GithubAbstractTemplateEngine class method returns the objectMap all values are available.

Demo renderings:

Add the dependent

MyBatis-Plus removed the default dependencies between code generators and template engines after 3.0.3, requiring manual addition of dependencies:

  • Adding code generator dependencies (mandatory)

    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-generator</artifactId>
        <version>3.4.2</version>
    </dependency>
    Copy the code
  • MyBatis-Plus supports Velocity (default), Freemarker, Beetl, etc. You can choose a template engine you are familiar with. If none of them meet your requirements, you can use a custom template engine. (One must be selected)

    Velocity (default) :

    <dependency>
        <groupId>org.apache.velocity</groupId>
        <artifactId>velocity-engine-core</artifactId>
        <version>2.3</version>
    </dependency>
    Copy the code

    A Freemarker:

    <dependency>
        <groupId>org.freemarker</groupId>
        <artifactId>freemarker</artifactId>
        <version>2.3.31</version>
    </dependency>
    Copy the code

    Beetl:

    <dependency>
        <groupId>com.ibeetl</groupId>
        <artifactId>beetl</artifactId>
        <version>3.3.2 rainfall distribution on 10-12. RELEASE</version>
    </dependency>
    Copy the code

    Attention! If you choose a non-default engine, you need to set up the template engine in AutoGenerator.

    AutoGenerator generator = new AutoGenerator();
    
    // set freemarker engine
    generator.setTemplateEngine(new FreemarkerTemplateEngine());
    
    // set beetl engine
    generator.setTemplateEngine(new BeetlTemplateEngine());
    
    // set custom engine (reference class is your custom engine class)
    generator.setTemplateEngine(new CustomTemplateEngine());
    
    // other config.Copy the code

coding

// Demo example, execute main method console input module table name press enter automatically generated corresponding project directory
public class CodeGenerator {

    /** * 

* 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 String projectPath = globalConfig(mpg); // Data source configuration dataSourceConfig(mpg); // Generate the package configuration PackageConfig pc = packageConfig(mpg); diyConfig(mpg, projectPath, pc); // Configure the template TemplateConfig templateConfig = new TemplateConfig(); // Configure a custom output template FTL /. Vm is automatically identified based on the template engine in use // templateConfig.setEntity("templates/entity2.java"); // templateConfig.setService(); // templateConfig.setController(); // The default XML generation location is in the same directory as mapper, which is not practical, instead of diyConfig custom resources/mapper templateConfig.setXml(null); mpg.setTemplate(templateConfig); // Policy configuration strategyConfig(mpg, pc); mpg.setTemplateEngine(new FreemarkerTemplateEngine()); mpg.execute(); } private static void diyConfig(AutoGenerator mpg, String projectPath, PackageConfig 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; }});/* 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. }}); * / // Customize the output file cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); } private static void strategyConfig(AutoGenerator mpg, PackageConfig pc) { StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); // "your own parent entity, no need to set!" / / strategy. SetSuperEntityClass (" your parent entity, there is no need not set!" ); // [entity] Lombok model (default false) strategy.setEntityLombokModel(true); // Generate the @restController controller strategy.setRestControllerStyle(true); // Public parent "your own parent controller, no need to set!" / / strategy. SetSuperControllerClass (" your parent controller, no need not set up!" ); // Public fields written in the parent class // strategy.setSuperEntityColumns("id"); strategy.setInclude(scanner("Table name, separated by multiple Commas").split(",")); strategy.setControllerMappingHyphenStyle(true); strategy.setTablePrefix(pc.getModuleName() + "_"); mpg.setStrategy(strategy); } private static PackageConfig packageConfig(AutoGenerator mpg) { PackageConfig pc = new PackageConfig(); // sys module name of the parent package pc.setModuleName(scanner("Module name")); // The parent package name. If it is empty, the next package name must be written all, otherwise only the subpackage name is written pc.setParent("com.laker.demo"); /** * The above code generation location and package name * com.laker.demo.sys */ mpg.setPackageInfo(pc); return pc; } private static void dataSourceConfig(AutoGenerator mpg) { DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/laker? useUnicode=true&useSSL=false&characterEncoding=utf8"); // dsc.setSchemaName("public"); dsc.setDriverName("com.mysql.cj.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("123456"); mpg.setDataSource(dsc); } private static String globalConfig(AutoGenerator mpg) { GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); // Generate the output directory of the file gc.setOutputDir(projectPath + "/src/main/java"); // Author name gc.setAuthor("laker"); // Whether to open the output directory gc.setOpen(true); // Entity attribute Swagger2 annotation // gc.setSwagger2(true); // Whether to overwrite existing files gc.setFileOverride(false); / / open BaseResultMap gc.setBaseResultMap(true); / / open baseColumnList gc.setBaseColumnList(true); mpg.setGlobalConfig(gc); returnprojectPath; }}Copy the code

For more detailed configuration, see the code generator configuration article.

Write the configuration

The MyBatis-Plus code generator provides a large number of custom parameters for users to choose from, and can satisfy the needs of most people.

  • Configuration GlobalConfig

    GlobalConfig globalConfig = new GlobalConfig();
    globalConfig.setOutputDir(System.getProperty("user.dir") + "/src/main/java");
    globalConfig.setAuthor("jobob");
    globalConfig.setOpen(false);
    Copy the code
  • Configuration DataSourceConfig

    DataSourceConfig dataSourceConfig = new DataSourceConfig();
    dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/ant? useUnicode=true&useSSL=false&characterEncoding=utf8");
    dataSourceConfig.setDriverName("com.mysql.jdbc.Driver");
    dataSourceConfig.setUsername("root");
    dataSourceConfig.setPassword("password");
    Copy the code

Custom template engine

A derived class, please com. Baomidou. Mybatisplus.. The generator engine. AbstractTemplateEngine

Custom code templates

The internal template is

/ / specify custom templates path, location: / resources/templates/entity2. Java. FTL (or vm).
// Be careful not to include.ftl(or.vm), which is automatically identified according to the template engine used
TemplateConfig templateConfig = new TemplateConfig()
    .setEntity("templates/entity2.java");

AutoGenerator mpg = new AutoGenerator();
// Configure a custom template
mpg.setTemplate(templateConfig);
Copy the code

Custom property injection

InjectionConfig injectionConfig = new InjectionConfig() {
    // Custom attribute injection: ABC
    // In the.ftl(or.vm) template, get the attributes with ${cfg. ABC}
    @Override
    public void initMap(a) {
        Map<String, Object> map = new HashMap<>();
        map.put("abc".this.getConfig().getGlobalConfig().getAuthor() + "-mp");
        this.setMap(map); }}; AutoGenerator mpg =new AutoGenerator();
// Configure custom attribute injectionmpg.setCfg(injectionConfig); Entity2.java.ftl custom attribute injection ABC =${cfg. ABC} Entity2.java.vm custom attribute injection ABC =$! {cfg.abc}Copy the code

Field Other information query injection

new DataSourceConfig().setDbQuery(new MySqlQuery() {

    SQL > alter table tableFieldsSql alter table tableFieldsSql alter table tableFieldsSql alter table tableFieldsSql Table. Fields gets all the field information, * then loop the field to get field. CustomMap Gets the injected fields from the MAP like NULL or PRIVILEGES */
    @Override
    public String[] fieldCustom() {
        return new String[]{"NULL"."PRIVILEGES"}; }})Copy the code

Practical summary

  • Mapper. XML: here the default XML generation location is in a directory with mapper, not practical, change to diyConfig custom resources/mapper under

  • GlobalConfig.setBaseResultMap(true)

        <! -- Query mapping result -->
        <resultMap id="BaseResultMap" type="com.laker.demo.sys.entity.User">
            <id column="id" property="id" />
            <result column="name" property="name" />
            <result column="age" property="age" />
            <result column="email" property="email" />
        </resultMap>
    Copy the code
  • GlobalConfig.setBaseColumnList(true)

        <! -- Generic query result column -->
        <sql id="Base_Column_List">
            id, name, age, email
        </sql>
    Copy the code
  • Add xxxmapper. XML

    mybatis-plus:
      mapper-locations: classpath*:/mapper/**/*.xml If mapper. XML is placed this way, it can be omitted
    Copy the code
  • A custom controller. Java. FTL

    code

            // Configure the template
            TemplateConfig templateConfig = new TemplateConfig();
            // Configure a custom output template
            FTL /. Vm is automatically identified based on the template engine in use
             templateConfig.setController("templates/controller.java");
    Copy the code

    The position of the template is in the picture below. Copy it and change it.

    package ${package.Controller}; import org.springframework.web.bind.annotation.RequestMapping; <#if restControllerStyle> import org.springframework.web.bind.annotation.RestController; <#else> import org.springframework.stereotype.Controller; </#if> <#if superControllerClassPackage?? > import ${superControllerClassPackage}; </#if> /** * <p> * ${table.comment! } Front Controller * </p> * * @author ${author} * @since ${date} */ <#if restControllerStyle> @restController <#else> @Controller </#if> @RequestMapping("<#if package.ModuleName?? && package.ModuleName ! = "">/${package.ModuleName}</#if>/<#if controllerMappingHyphenStyle?? >${controllerMappingHyphen}<#else>${table.entityPath}</#if>") <#if kotlin> class ${table.controllerName}<#if superControllerClass?? > : ${superControllerClass}()</#if> <#else> <#if superControllerClass?? > public class ${table.controllerName} extends ${superControllerClass} { <#else> public class ${table.controllerName} { </#if> } </#if>Copy the code
  • Experience in specification

    • Table named resource_highway

      Enter the module name: resource Enter the table name, separated by commas: resource_highwayCopy the code
    • The generated package com.laker.demo.resource

      • controller.HighwayController

Commonly used to summarize

Multi-table LianZha

  • Complex: Write it directly in XML

  • Simple: Annotation programming + associated result VO

    public interface QuestionMapper extends BaseMapper<Question> {
        //Page page-turning object, which can be used directly as an XML parameter. Passing the parameter page automatically page-turning@Select("SELECT t_question.*,t_student.`name` FROM t_question,t_student WHERE t_question.student_id=t_student.id")
        List<QuestionStudentVO> getQuestionStudent(Pagination page);
    }
    Copy the code

Enabling Log Printing

general

logging:
  level:
    com.xxx.mapper: debug
Copy the code

Mybatis-Plus

This can only be logged on the console

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
Copy the code

PerformanceInterceptor, although the higher version (3.1.0 +) has been removed, we can still learn from it.

To copy the code directly to your local site, use the following two classes

Step 1: Configure the plug-in in the MP configuration class and only for the DEV environment

// MybatisPlus configuration class
@Configuration
public class MyBatisPlusConfig {
    //SQL execution efficiency plug-in
    @Bean
    @Profile({"dev"}) // Specifies that the environment takes effect for dev
    public PerformanceInterceptor performanceInterceptor(a) {
        PerformanceInterceptor interceptor = new PerformanceInterceptor();
        // SQL beautify print
        interceptor.setFormat(true);
        // Set the SQL timeout period
        interceptor.setMaxTime(5000L);
        // Write to the log
        interceptor.setWriteInLog(true);
        returninterceptor; }}Copy the code

Step 2: Set the environment to dev.

spring:
  profiles:
    active: dev
Copy the code

The results are as follows:

2021- 03- 09 19:57:10.925  INFO 20232 [nio - 8080 - exec - 1] c.a.h.d.com mon. PerformanceInterceptor: Time: 15 ms - ID: com. The laker. Demo. Mapper. StakeMapper. Insert
Execute SQL:INSERT 
    INTO
        resource_stake
        ( road_id, stake_name, state_num, direction, picture_url, lon, lat ) 
    VALUES
        ( 0.'string'.0.'string'.'string'.0.0 )
Copy the code

Mybatis

mybatis:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
Copy the code

Update and delete

Updates and deletes are processed by defaultNot nullfield


Write more CSDN good card, and save always audit, then open a, in the “from zero to build development scaffolding” column search

Mybatis- Plus ii – Build scaffolding from Scratch with Spring Boot

Public accounts will continue to output high-quality articles, and common progress.