Mybatis plus upgrade complete! What has my system been updated? What's better about mybatis plus than mybatis?

Keywords: Database Mybatis Spring Boot Vue.js

Mybatis plus upgrade complete! What has my system been updated? What's better about mybatis plus than mybatis?

I've been writing about the system for nearly a month. Generally speaking, I upgraded my Mybatis to Mybatis plus, but it's not exactly like this. There are many small changes. This time, I specially wrote a blog to record the update log of the system and put an end to the Vue – SpringBoot – Mybatis plus system!

1, Clear warnings and non-standard and unnecessary codes

Because the system was completed in 7 days, there are many codes written to save trouble, including some code duplication, outdated references and warnings.
This update completely solves the above contents and achieves the perfect compilation of back-end code on JDK8 and IDEA2021.2.1 without warning! No error!
This is the IDEA detection data before the change. After careful calculation, there are 341 warnings. It can be called a program running on warnings!

After the change, there is still a sense of achievement (there may be a warning to eliminate obsessive-compulsive disorder...)

2, Redrawn the interface and change the theme color

The previous system was learned online, so the color is similar to that of others. Taking the opportunity to update the system, I also redesigned the theme of the front-end web page.
This is the previous theme color:

This is the updated theme color (it may be more ugly, but it took me all morning to color it anyway (^▽^))

3, Interface without ID

Due to the database design, the association between many tables must use ID as a bridge. At that time, the design was too rough, and the ID was directly displayed on the interface instead of the Name. However, in real life, the user saw the Name instead of a string of numbers, which should be regarded as a serious design vulnerability at that time (it was too hard to change), Here's a trick. When designing the database in the future, you can add a Name column associated with it after the ID, and change the place where the ID is displayed in the front end to Name (although it will cause data redundancy, it's really easy to change. Just be lazy)
Before update (it's unreasonable to see now)

After update

4, Upgrade Mybatis to Mybatis plus

This can be said to be the most important point. After upgrading Mybatis plus, you don't need to write an SQL statement. People who have written SQL statements know that designing multi table queries is torture. Although I used Navicat to automatically generate SQL statements at that time, I didn't find any shortcut. Moreover, many operations involve the same kind of operations (such as finding a piece of data according to ID and looking up all the data in the table). There is no way to provide an interface with a unified method using Mybatis. Moreover, it was written in a hurry and no unified method was designed. Using Mybatis plus, one row of selectList can be solved.
Before update (very troublesome):
controller layer:
@RequestMapping("/equipmentHire")
    public String updateFactoryHire(@RequestParam("id") Integer id,
                                    @RequestParam("hire") int hire) {
        int i = udao.updateHire(id, hire);
        String str = i > 0 ? "success" : "error";
        return str;
    }
dao layer:
public int updateHire(Integer id, int hire);
mapper file:
	<update id="updateHire">
        UPDATE equipment
        SET e_hire = #{hire}
        WHERE e_id = #{id}
    </update>
After update (very simple and easy to maintain):
@RequestMapping("/equipmentHire")
    public String updateFactoryHire(@RequestParam("id") Long id,
                                    @RequestParam("hire") int hire) {

        Equipment equipment = new Equipment();
        equipment.setE_hire(hire);

        QueryWrapper<Equipment> wrapper = new QueryWrapper<>();
        wrapper.eq("e_id", id);


        int i = equipmentMapper.update(equipment, wrapper);
        return i > 0 ? "success" : "error";
    }

5, Update primary key ID form

In the past, the primary key ID was in the form of gradual increase in the database, but students who have used the default increase in the database will know that once the data is manually deleted during debugging, the ID will be discontinuous (and the ID of an object is 1, which is a little hard to see...). After mybatis plus is adopted this time, the primary key ID adopts SnowFlake (SnowFlake algorithm), Without going through the database, the ID is completely generated by the code, and the uniqueness is very high, and there is basically no duplication. Because the ID generated by the SnowFlake algorithm is a Long integer, many problems will occur when it is transmitted to the front end. Here is a solution (^ ▽^)

Snowflake algorithm
What if the Long type data returned by springboot Vue mybatisplus to the front end loses precision? The Long type is used as an attribute of the entity class
The Long type loses precision when passed to the front end (2): the Long type is not a field of the entity class, and the Long type is the return value of a function

6, Added optimistic lock


Here you can see that the optimistic lock plug-in works

7, Added logical deletion, addition time and update time (all automatically executed by mybatis plus)

Through the logical deletion component of mybatis plus and the automatic filling component of metadata (Meta), you can realize logical deletion or automatically fill the current time when adding (updating) the database.
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {

        log.info("start insert fill.....");
        this.setFieldValByName("gmt_create", new Date(), metaObject);
        this.setFieldValByName("gmt_modified", new Date(), metaObject);

    }

    @Override
    public void updateFill(MetaObject metaObject) {

        log.info("start update fill.....");
        this.setFieldValByName("gmt_modified", new Date(), metaObject);

    }
}
// Delete components logically!
    @Bean
    public ISqlInjector sqlInjector() {

        return new LogicSqlInjector();
    }

Here you can see that mybatis plus is similar to JDBC when running: first use prepareStatement to build SQL statements, then use placeholder (?) to assign variables, and finally operate the database.
The red arrow below also indicates that the ID, creation time and update time of the snowflake algorithm are automatically generated, not artificially written in the code

8, New SQL efficiency analysis

Through mybatis plus, you can control the execution efficiency of SQL statements!
//SQL execution efficiency plug-in
    // Set the dev test environment on to ensure our efficiency
    @Bean
    @Profile({"dev", "test"})
    public PerformanceInterceptor performanceInterceptor() {
        PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();

        //  ms sets the maximum time for sql execution. If it exceeds, it will not be executed
        performanceInterceptor.setMaxTime(100);

        // Format code
        performanceInterceptor.setFormat(true);

        return performanceInterceptor;
    }

It can be seen here that the execution time of a select statement is 3 milliseconds, which is less than the predetermined 100 milliseconds. It can be executed!

If the SQL execution time is set to 1 ms (in fact, we know that 1 ms can't do anything), you can see that mybatis plus terminates the execution of the SQL statement (the execution of the SQL statement is too large, please optimize!). In this way, we can passively optimize the code according to the SQL efficiency analysis plug-in!

9, Automatic code generator

After designing the database, it is too troublesome to design the entity class with similar operation again. Mybatis plus has designed an automatic code generator for this purpose. According to the design of the database, it can generate bean layer, dao layer and controller layer with one click! It is very convenient, and you can choose a series of choices, such as package strategy, underline to hump, etc
Database design:

Automatically generated code structure:

Automatically generated entity classes:
package com.neu.edu.cloudfactoryplus.bean;

import com.baomidou.mybatisplus.annotation.IdType;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.Version;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

/**
 * <p>
 * 
 * </p>
 *
 * @author duzhenyang
 * @since 2021-09-14
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class Agency implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * Primary key ID
     */
    @TableId(value = "a_id", type = IdType.ID_WORKER)
    private Long a_id;

    /**
     * user name
     */
    private String a_name;

    /**
     * password
     */
    private String a_password;

    /**
     * Real name
     */
    private String a_realName;

    /**
     * contact information
     */
    private String a_contact;

    /**
     * Optimistic lock
     */
    @Version
    private Integer version;

    /**
     * Logical deletion
     */
    @TableLogic
    private Integer deleted;

    /**
     * Creation time
     */
    @TableField(fill = FieldFill.INSERT)
    private Date gmt_create;

    /**
     * Modification time
     */
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date gmt_modified;


}

It can be seen that the efficiency is still very high and the effect is also good!

10, Sprinkle flowers at the end

Here, the mybatis plus upgrade process has also come to an end. This summary has also been written for two days. There are many new contents in the upgrade process. I don't know whether they are completely written for a while. In the future, new updates will be added!!!
Mybatis plus bye!
Hello Linux!

Posted by JParishy on Thu, 18 Nov 2021 20:25:28 -0800