Some uses of mybatis plus

Introduction

Official website: http://mp.baomidou.com/
Reference tutorial: https://baomidou.com/pages/24112f/
MyBatis-Plus (MP for short) is an enhancement tool for MyBatis. It only enhances and does not Make changes to simplify development and improve efficiency.

characteristic

  • No intrusion: only enhancement and no change, the introduction of it will not affect the existing project, as smooth as silk.
  • Low loss: Basic CURD will be automatically injected upon startup, with basically no performance loss and direct object-oriented operation.
  • Powerful CRUD operations: Built-in general Mapper and general Service, most CRUD operations on a single table can be implemented with only a small amount of configuration. There are also powerful conditional constructors to meet various usage needs.
  • Support Lambda form invocation: Through Lambda expressions, it is convenient to write various query conditions, and there is no need to worry about field typos.
  • Supports automatic generation of primary keys: supports up to 4 primary key strategies (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, the entity class only needs to inherit the Model class to perform powerful CRUD operations.
  • Support custom global general operations: support global general method injection ( Write once, use anywhere ).
  • Built-in code generator: Use code or Maven plug-ins to quickly generate Mapper, Model, Service, and Controller layer codes. It supports template engines and has many custom configurations waiting for 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, writing paging is equivalent to ordinary List query.
  • The pagination plug-in supports multiple databases: supports MySQL, MariaDB, Oracle, DB2, H2, HSQL, SQLite, Postgre, SQLServer and other databases.
  • Built-in performance analysis plug-in: can output SQL statements and their execution time. It is recommended to enable this function during development and testing to quickly identify slow queries.
  • Built-in global interception plug-in: Provides intelligent analysis and blocking of delete and update operations in the entire table. Interception rules can also be customized to prevent misoperations.

Configure database environment

DROP TABLE IF EXISTS user;

CREATE TABLE user
(
    id BIGINT(20) NOT NULL COMMENT '主键ID',
    name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
    age INT(11) NULL DEFAULT NULL COMMENT '年龄',
    email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
    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]');

springboot project environment

1. Use Spring Initializr to quickly initialize a Spring Boot project

2. Introduce dependencies

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!--mybatis-plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.2</version>
        </dependency>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!--lombok用来简化实体类-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

3. Add related configuration of MySQL database

#mysql数据库连接
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis-plus?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=zzybzb

4. Add the @MapperScan annotation to the Spring Boot startup class to scan the Mapper folderinsert image description here

5. Create the package entity and write the entity class User.java (Lombok is used to simplify the code here)insert image description here

6. Create the package mapper and write the Mapper interface: UserMapper.javainsert image description here

7. Add a test class for functional testing:

@SpringBootTest
@RunWith(SpringRunner.class)
public class MybatisPlusApplicationTests {
    
    

    @Autowired
    UserMapper userMapper;

    /**
     * 查询所有数据
     */
    @Test
    public void testList() {
    
    
        List<User> users = userMapper.selectList(null);
        users.forEach(System.out::println);
    }

}

operation result:

User(id=1, name=Jone, age=18, [email protected])
User(id=2, name=Jack, age=20, [email protected])
User(id=3, name=Tom, age=28, [email protected])
User(id=4, name=Sandy, age=21, [email protected])
User(id=5, name=Billie, age=24, [email protected])

Insert operation (insert)

    @Test
    public void testInsert(){
    
    
        User user = new User();
        user.setName("李四");
        user.setAge(18);
        user.setEmail("[email protected]");
        int result = userMapper.insert(user);
        System.out.println(result); //影响的行数
        System.out.println(user); //id自动回填
    }

insert image description here

Tombstone

Add plugin to configuration class

    /**
     * 逻辑删除插件
     */
    @Bean
    public ISqlInjector sqlInjector() {
    
    
        return new LogicSqlInjector();
    }

Add annotations to entity classes: @TableLogic
insert image description here

Use directly
insert image description here

Autofill (automatically generate creation time and modification time)

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    
    
    /**
     * 新增的方法
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
    
    
        //属性名称,不是字段名称
        this.setFieldValByName("gmtCreate", new Date(), metaObject);
        this.setFieldValByName("gmtModified", new Date(), metaObject);
    }
    /**
     * 修改的方法
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
    
    
        this.setFieldValByName("gmtModified", new Date(), metaObject);
    }
}

Add annotations to fields

@TableField(fill = FieldFill.INSERT)
@TableField(fill = FieldFill.INSERT_UPDATE)

insert image description here

Time field can be ignored when adding data
insert image description here

I feel like the writing is not good enough. Please check the official website for details: https://baomidou.com/

Finish!
hy:22


					感受生命中的每个瞬间,你会发现它们都是如此美好。

Guess you like

Origin blog.csdn.net/weixin_49107940/article/details/126772222