Collect it now! Mybatis plus ten thousand words graphic notes. If you miss this village, you won’t have this shop

Time:2021-6-10

brief introduction

Mybatis plus (MP) is a   The enhancement tool of mybatis, based on mybatis, only enhances and does not change. It is created to simplify development and improve efficiency

vision

Our vision is to be the best partner for mybatis, like   Contra   In 1p, 2p, base friend collocation, efficiency doubled.

Collect it now! Mybatis plus ten thousand words graphic notes. If you miss this village, you won't have this shop

characteristic

  • No invasion: only strengthen without change, the introduction of it will not have an impact on the existing project, as smooth as silk
  • Low loss: basic curd will be automatically injected at startup, with no performance loss and direct object-oriented operation
  • Powerful crud operation: built in general mapper and general service, most CRUD operations of single table can be realized with only a small amount of configuration, and more powerful condition constructor can meet all kinds of use requirements
  • Support lambda form call: through lambda expression, it is convenient to write all kinds of query conditions without worrying about wrong fields
  • Support automatic generation of primary key: support up to four primary key policies (including distributed unique ID generator – sequence), which can be freely configured to perfectly solve the primary key problem
  • Support activerecord mode: support activerecord form call, entity class only needs to inherit model class to perform powerful crud operation
  • Support custom global general operations: support global general method injection (write once, use anywhere)
  • Built in code generator: mapper, model, service and controller layer code can be generated quickly by using code or Maven plug-in. Template engine is supported, and there are more custom configurations for you to use
  • Built in paging plug-in: Based on mybatis physical paging, developers don’t need to care about specific operations. After configuring the plug-in, writing paging is equivalent to ordinary list query
  • The paging plug-in supports multiple databases: support mysql, MariaDB, Oracle, DB2, H2, hsql, SQLite, postgre, SQL server and other databases
  • Built in performance analysis plug-in: it can output SQL statement and its execution time. It is recommended to enable this function when developing and testing, which can quickly find out slow queries
  • Built in global interception plug-in: provide intelligent analysis blocking for delete and update operation of the whole table, and also customize interception rules to prevent misoperation

Frame structure

Collect it now! Mybatis plus ten thousand words graphic notes. If you miss this village, you won't have this shop

quick get start

  • Create database table (mybatis — plus)
  • Create user table**
DROP TABLE IF EXISTS user;
CREATE TABLE user
(
ID bigint (20) not null comment 'primary key ID',
Name varchar (30) null default null comment 'name',
Age int (11) null default null comment 'age',
Email varchar (50) null default null comment 'mailbox',
PRIMARY KEY (id)
);
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, '[email protected]'),
(2, 'Jack', 20, '[email protected]'),
(3, 'Tom', 28, '[email protected]'),
(4, 'Sandy', 21, '[email protected]'),
(5, 'Billie', 24, '[email protected]');
  • Write the project, initialize the project! Use springboot to initialize!
  • Import dependency
<!--  Database driver -- >
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>
<!-- mybatis-plus -->
<!--  Just use mybatis plus instead of importing mybatis -- >
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.0.5</version>
</dependency>
  • Configuration database in YML file**
spring:
  datasource:
    password: 123456
    username: root
    url: jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
    driver-class-name: com.mysql.jdbc.Driver
  • Write POJO class and mapper interface**
  • pojo
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}
  • Mapper interface, inheriting basemapper

    @Repository // represents the persistence layer
    public interface UserMapper extends BaseMapper<User> {
        //There is no need to write in it
    }
  • Start class add mapper scan

    @MapperScan("com.alan.mybatis.plus.mapper")
    
  • Test in test class

    @SpringBootTest
    class MybatisPlusApplicationTests {
        @Autowired
        private UserMapper userMapper;
    
        @Test
        void contextLoads() {
            //Inquiry
            List<User> users = userMapper.selectList(null);
            users.forEach(System.out::println);
        }
    
    }
  • result

    Collect it now! Mybatis plus ten thousand words graphic notes. If you miss this village, you won't have this shop

  • Add log
  • Configure YML

    mybatis-plus:
      configuration:
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    
  • result

    Collect it now! Mybatis plus ten thousand words graphic notes. If you miss this village, you won't have this shop

Crud extension

Insert operation

Insert

@Test
public void testInsert(){
    User user = new User();
    User. Setname ("Turing");
    user.setAge(20);
    user.setEmail("[email protected]");
    //Result is the number of rows affected
    int result = userMapper.insert(user);
    System.out.println(result);
    //Automatic ID backfill, default snowflake algorithm
    System.out.println(user);
}

Collect it now! Mybatis plus ten thousand words graphic notes. If you miss this village, you won't have this shop

The default value of ID inserted in database is: globally unique ID

Primary key generation strategy

1. Snowflake algorithm:

Snowflake is Twitter’s open source distributed ID generation algorithm, and the result is a long ID. Its core idea is: using 41bit as the
The number of milliseconds, 10bit as the ID of the machine (5 bits for the data center, 5 bits for the machine ID), 12bit as the serial number within milliseconds (meaning
This means that each node can generate 4096 IDS per millisecond), and finally there is a sign bit, which is always 0. Can guarantee almost global security
One!

2. Primary key auto increment

2.1 you need to add@TableId(type = IdType.AUTO)

2.2 the fields corresponding to the database must be self increasing

Collect it now! Mybatis plus ten thousand words graphic notes. If you miss this village, you won't have this shop

2.3 results

Collect it now! Mybatis plus ten thousand words graphic notes. If you miss this village, you won't have this shop

Other source code explanation

public enum IdType {
    Auto (0), // database ID auto increment
    None (1), // no primary key set
    Input (2), // input manually
    ID_ Work (3), // default globally unique ID
    UUID (4), // globally unique ID UUID
    ID_ WORKER_ STR(5);// ID_ Work string representation 
}

update operation


@Test
public void testUpdate(){
    User user = new User();
    user.setId(1334744418774695938L);
    //Only the age is changed here
    user.setAge(19);
    int i = userMapper.updateById(user);
    System.out.println(i);
}

Update operation is dynamic SQL

Collect it now! Mybatis plus ten thousand words graphic notes. If you miss this village, you won't have this shop

Auto fill


Create time, modify time! These operations are all done automatically. We don’t want to update them manually!
Alibaba Development Manual: all database tables: GMT_ create、gmt_ Modified almost all tables need to be configured! And it needs automation!

Code level

  • modify the database

Collect it now! Mybatis plus ten thousand words graphic notes. If you miss this village, you won't have this shop

  • Modify the entity class and add notes to the time attribute
Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    @TableId(type = IdType.AUTO)
    private Long id;
    private String name;
    private Integer age;
    private String email;

    @TableField(fill = FieldFill.INSERT)
    private Date createTime;

    @TableField(fill = FieldFill.INSERT_UPDATE)
    private Date UpdateTime;
}

@Tablefield (fill = fieldfill. Insert) updates the time when creating a new data.

@TableField(fill = FieldFill.INSERT_ Update), when creating and updating this data, the update time.

  • Write configuration class

    @Slf4j
    @Component // the class is added to the IOC container when the annotation is used
    public class MyMetaObjectHandler implements MetaObjectHandler {
        //Policy when inserting
        @Override
        public void insertFill(MetaObject metaObject) {
            log.info("start insert fill.....");
            this.setFieldValByName("createTime",new Date(),metaObject);
            this.setFieldValByName("updateTime",new Date(),metaObject);
        }
        //Update policy
        @Override
        public void updateFill(MetaObject metaObject) {
            log.info("start update fill.....");
            this.setFieldValByName("updateTime",new Date(),metaObject);
        }
    }

Run add and modify respectively

Collect it now! Mybatis plus ten thousand words graphic notes. If you miss this village, you won't have this shop

Paging query

1. Write configuration class, interceptor

package com.alan.mybatis.plus.config;

import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.extension.injector.LogicSqlInjector;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

/**
 * @Author Alan Ture
 * @Description
 */
@Configuration
public class MyBatisPlusConfig {
    /**
     *Paging plug in
      */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

}

2. You can use the page object directly.

//Paging test query
@Test
public void testPage(){
    //Parameter 1: current page
    //Parameter 2: page size
    Page<User> page = new Page<>(1,5);
    userMapper.selectPage(page,null);
    page.getRecords().forEach(System.out::println);
    System.out.println(page.getTotal());
}

Delete operation

1. Delete records by ID

//Test delete
@Test
public void testDeleteById(){
    userMapper.deleteById(1334744418774695938L);
}

//Batch deletion by ID
@Test
public void testDeleteBatchId(){
    userMapper.deleteBatchIds(Arrays.asList(1334745985150111745L,1334745985150111746L));
}
//Delete by map
@Test
public void testDeleteMap() {
    HashMap<String, Object> map = new HashMap<>();
    Map. Put ("name", "Turing");
    userMapper.deleteByMap(map);
}

Logical deletion

Physical delete: remove directly from database
Logical deletion: the database is not removed, but through a variable to make it invalid! deleted = 0 => deleted = 1

1. Database add field

Collect it now! Mybatis plus ten thousand words graphic notes. If you miss this village, you won't have this shop

2. The entity class adds fields and comments

@Tablelogic // logical deletion
private Integer deleted;

3. Configuration class configuration

//Delete component logically!
@Bean
public ISqlInjector sqlInjector() {
    return new LogicSqlInjector();
}

4. YML configuration (deleted as 0, not deleted as 1)

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  global-config:
    db-config:
      logic-delete-value: 0
      logic-not-delete-value: 1

5. Test delete

//Test delete
@Test
public void testDeleteById(){
    userMapper.deleteById(1L);
}

The actual way is to update the operation

Collect it now! Mybatis plus ten thousand words graphic notes. If you miss this village, you won't have this shop

result

Collect it now! Mybatis plus ten thousand words graphic notes. If you miss this village, you won't have this shop

Performance analysis plug in

In our usual development, we will encounter some slow SQL. Test! druid,
Function: performance analysis interceptor, used to output each SQL statement and its execution time
MP also provides performance analysis plug-in, if it exceeds this time, it will stop running!

1. Import plug-ins (remember to configure the environment as dev or test in springboot!)

Properties.yml setting the development environment

spring:
  profiles:
    active: dev
/**
  *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(10);
    //Format code
    performanceInterceptor.setFormat(true);
    return performanceInterceptor;
}

2. Test use (abnormal will be reported if it exceeds the specified time)

Collect it now! Mybatis plus ten thousand words graphic notes. If you miss this village, you won't have this shop

Conditional constructor wrapper

We can use it to replace some complex SQL!

Collect it now! Mybatis plus ten thousand words graphic notes. If you miss this village, you won't have this shop

1. In test 1, isnotnull is not null and Ge is greater than or equal to

@Test
public void contextLoads() {
//Query the user whose name is not empty and whose mailbox is not empty, whose age is greater than or equal to 12
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper
            .isNotNull("name")
            .isNotNull("email")
            .ge("age",20);
    userMapper.selectList(wrapper).forEach(System.out::println);
    //Compare it with the map we just learned

}

Collect it now! Mybatis plus ten thousand words graphic notes. If you miss this village, you won't have this shop

2. In test 2, EQ queries equal data

@Test
public void test2(){
    //Query name Jone
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.eq("name","Jone");
    User user = userMapper.selectOne(wrapper);
    //Query a data, multiple results using list or map
    System.out.println(user);
}

Collect it now! Mybatis plus ten thousand words graphic notes. If you miss this village, you won't have this shop

Automatic code generator

package com.alan.mybatis.plus;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.util.ArrayList;

//Automatic code generator
public class GenCode {
    public static void main(String[] args) {
//You need to build an automatic code generator object
        AutoGenerator mpg = new AutoGenerator();
//Configuration policy
//1. Global configuration
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("Alan Ture");
        gc.setOpen(false);
        gc.setFileOverride(false); //  Is it covered
        gc.setServiceName("%sService"); //  I prefix to service
        gc.setIdType(IdType.ID_WORKER);
        gc.setDateType(DateType.ONLY_DATE);
        gc.setSwagger2(true);
        mpg.setGlobalConfig(gc);
//2. Set data source
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/mybatis_plus? useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        dsc.setDbType(DbType.MYSQL);
        mpg.setDataSource(dsc);
//3. Package configuration
        PackageConfig pc = new PackageConfig();
        pc.setModuleName("blog");
        pc.setParent("com.alan");
        pc.setEntity("entity");
        pc.setMapper("mapper");
        pc.setService("service");
        pc.setController("controller");
        mpg.setPackageInfo(pc);
//4. Policy configuration
        StrategyConfig strategy = new StrategyConfig();
        strategy.setInclude("user"); //  Set the name of the table to map
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true); //  Automatic Lombok;
        strategy.setLogicDeleteFieldName("deleted");
//Auto fill configuration
        TableFill gmtCreate = new TableFill("create_time", FieldFill.INSERT);
        TableFill gmtModified = new TableFill("update_time",
                FieldFill.INSERT_UPDATE);
        ArrayList<TableFill> tableFills = new ArrayList<>();
        tableFills.add(gmtCreate);
        tableFills.add(gmtModified);
        strategy.setTableFillList(tableFills);
//Optimistic lock
//        strategy.setVersionFieldName("version");
//        strategy.setRestControllerStyle(true);
//        strategy.setControllerMappingHyphenStyle(true); //localhost:8080/hello_id_2
        mpg.setStrategy(strategy);
        mpg.execute(); // implement
    }
}

last

Finally, we provide free learning materials on Java architecture, including: spring, Dubbo, mybatis, RPC, source code analysis, high concurrency, high performance, distributed, performance optimization, microservice advanced architecture development, etc. Welcome to my official account: bright future!
Collect it now! Mybatis plus ten thousand words graphic notes. If you miss this village, you won't have this shop