MyBatis Plus rookie quick start

Posted by Brad420 on Tue, 05 Oct 2021 23:11:59 +0200

MyBatis Plus

Domestic open source framework based on MyBatis

The core function is to simplify the development of MyBatis and improve efficiency.

MyBatis Plus quick start

1. Create a springboot project

2. Import the dependency of mybatisplus

		<dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.1.tmp</version>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.3.1.tmp</version>
        </dependency>

3. Create the entity class Users (you can define a relatively simple table)

package com.bdh.mybatisplustest.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Users {
    private Integer id;
    private String username;
    private Integer password;
}

4. Create Mapper interface

package com.bdh.mybatisplustest.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.bdh.mybatispulstest.entity.Users;

//Inject into mybatis puls
public interface  UserMapper extends BaseMapper<Users> {

}

5. Add the myatispulstapplication annotation * @ MapperScan("com.xxx.xxx.mapper") * on the startup class, otherwise the Mapper bean cannot be loaded.

package com.bdh.mybatisplustest;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.bdh.myatispulstest.mapper")
public class MyatispulstestApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyatispulstestApplication.class, args);
    }

}

6. Create a springboot test

package com.bdh.mybatisplustest.mapper;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class UserMapperTest {
    @Autowired
    private UserMapper mapper;

    @Test
    void test(){
        mapper.selectList(null).forEach(System.out::println);
    }
}

Common notes

@TableName(value = "xxxx")

Table name of the mapping database

package com.bdh.mybatisplustest.entity;

import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName(value = "users")
public class TestName {
    private Integer id;
    private String username;
    private Integer password;
}

*@Difference between TableId(value = "xxxx") and @ TableField(value = "xxxx") *

@TableId(value = "xxxx") refers specifically to the modification on the primary key. So what I changed in the picture is to set the primary key type and the primary key generation strategy in the type attribute of the primary key field

@TableField(value = "xxxx") mainly modifies non primary key fields, as shown in the figure. exist indicates whether it is a database field, select indicates whether to query a field, and fill indicates whether to fill it automatically

@What do you need to know under the type attribute in TableId(type = "xxxx")

AUTO(0),
NONE(1),
INPUT(2),
ASSIGN_ID(3),
ASSIGN_UUID(4),
//The last three are eliminated. Of course, you can use them if you want to play
/** @deprecated */
@Deprecated
ID_WORKER(3),
/** @deprecated */
@Deprecated
ID_WORKER_STR(3),
/** @deprecated */
@Deprecated
UUID(4);
describevalue
Database self incrementAUTO
MP (mybatis plus) (used by default) set primary key, implemented by snowflake algorithmNONE
Manual assignment by the developer is requiredINPUT
MP allocation ID, primary key type: Long, integer, stringASSIGN_ID
Allocate UUID, primary key type: StringASSIGN_UUID

AUTO literally means AUTO increment, and AUTO increment is greater than manual assignment.

In the NONE attribute, the id value in the snowflake algorithm is very large. If you use this attribute, you need to modify the length and attribute of the database field, and so does the entity.

INPUT attribute if you do not actively set the id value, the database will increase one of them to fill in the value.

ASSIGN_ As the default, IDS are injected using the snowflake algorithm.

ASSIGN_ The assignment of UUID attribute must be of String type, and the String of UUID will be generated for assignment#

@Usage and function of exits attribute in TableField(exits = "false")

Exits determines whether it is a field in the database. If it is not false, if it is true, if there is no corresponding field in the entity class, we can use exits, VO and DTO.

@Usage and function of exits attribute in TableField(fill = "DEFAULT")

Fill indicates whether to automatically fill in and store objects in the database, such as time and other information

public enum FieldFill {
    //Literally
    DEFAULT,
    INSERT,
    UPDATE,
    INSERT_UPDATE;

    private FieldFill() {
    }
}

1. Add fill to the automatically filled field to be added

package com.bdh.myatisplustest.entity;

import com.baomidou.mybatisplus.annotation.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName(value = "users")
public class TageName {
    @TableId(value = "id",type = IdType.INPUT)
    private Integer bid;
    @TableField(value = "username")
    private String name;
    private String password;
    @TableField(exist = false)
    private String test;
    @TableField(fill = FieldFill.INSERT)
    private Data createTime;
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Data updateTime;

}

2. Create handler configuration class

package com.bdh.myatispulstest.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("createTime",new Date(),metaObject);
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime",new Date(),metaObject);

    }
}

3. Test

@Annotation of version mybatis plus optimistic lock

I won't talk about this annotation. If you have a solid foundation in multithreading, it's naturally very simple. If you can't, it's more difficult. Of course, I will simply say the use and principle, such as

After update xxxx, version will be changed under MP. For example, version 1 becomes version 2 after we modify a certain data, and another brother just modifies the same field as you. Then, because you modify this field first, his version is already 2 at the moment you modify it. Then, the good brother made an execution error because the version changed to 2 (generally, the logic of not executing is not tenable). That's about it

Usage is

1. Add notes

import com.baomidou.mybatisplus.annotation.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Date;

@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName(value = "users")
public class TageName {
    @TableId(value = "id",type = IdType.INPUT)
    private Integer bid;
    @TableField(value = "username")
    private String name;
    private String password;
    @TableField(value = "createTime",fill = FieldFill.INSERT)
    private Date createTime;
    @TableField(value = "updateTime",fill = FieldFill.INSERT_UPDATE)
    private Date updateTime;
    @Version
    private int version;

}

2. Write configuration class

package com.bdh.myatispulstest.config;

import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyBatisPlusConfig {

    public OptimisticLockerInterceptor optimisticLockerInterceptor(){
        return new OptimisticLockerInterceptor();
    }
}

3. Successful test

@EnumValue enumeration operation is no different from ordinary enumeration. There are mainly two implementations: one is interface implementation, and the other is configuration implementation

Configuration implementation:

package com.bdh.myatispulstest.enums;

import com.baomidou.mybatisplus.annotation.EnumValue;

public enum StatusEnum {
    Test1(0,"success"),
    Test2(1,"success");


    StatusEnum(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    @EnumValue
    private Integer code;
    private String msg;

}

Interface implementation:

Don't knock a lot of these things here. You can just learn from others

umValue;

public enum StatusEnum {
Test1(0, "success"),
Test2(1,"success");

StatusEnum(Integer code, String msg) {
    this.code = code;
    this.msg = msg;
}

@EnumValue
private Integer code;
private String msg;

}

Topics: Java Mybatis Spring Spring Boot