Spring boot integrates mybatis plus crud operation

1 . Introducing mybatis plus

mybatis plus (opens new window) (MP for short) is an enhancement tool of MyBatis (opens new window). On the basis of mybatis, it only makes enhancement without change, and is born to simplify development and improve efficiency. But for the join table operation, you must also use mybatis

2 . characteristic

  • No invasion: it is only enhanced without change, and its introduction will not affect the existing project, which is as smooth as silk

  • Low loss: the basic CURD will be injected automatically upon startup, with basically no loss of performance and direct object-oriented operation

  • Powerful crud operation: built-in general Mapper and general Service. Most CRUD operations of a single table can be realized only through a small number of configurations. There is also a powerful condition constructor to meet various use needs

  • Support Lambda form call: through Lambda expression, it is convenient to write various query conditions, and there is no need to worry about the wrong field JDK1

  • Support automatic generation of primary key: support up to 4 primary key strategies (including distributed unique ID generator - Sequence), which can be configured freely to perfectly solve the problem of primary key

  • Support ActiveRecord mode: support ActiveRecord formal calls. Entity classes only need to inherit Model classes to perform powerful CRUD operations

  • Support custom global general operations: support global general method injection (Write once, use anywhere)

  • Built in code generator: code or Maven plug-in can be used to quickly generate Mapper, Model, Service and Controller layer code, support template engine, and have more custom configurations 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 paging plug-in supports multiple databases: MySQL, MariaDB, Oracle, DB2, H2, HSQL, SQLite, Postgre, SQLServer and other databases

  • Built in performance analysis plug-in: it can output 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: it provides intelligent analysis and blocking of full table delete and update operations, and can also customize interception rules to prevent misoperation

3. How to use

1. Create a springboot project and add related dependencies

 <!--①Introduce related dependencies-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.1</version>
        </dependency>

2. Configuration file

spring.datasource.druid.username=root
spring.datasource.druid.password=196055
spring.datasource.druid.url=jdbc:mysql://localhost:3306/twosupper?serverTimezone=Asia/Shanghai
spring.datasource.druid.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.druid.max-active=5

#Print file log
logging.level.com.mybasicplus.mapper=debug 

3. Entity class

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

4. Interface mapper

public interface EmpMapper extends BaseMapper<User> {

}

5. Scan mapper on the main startup class

@SpringBootApplication
@MapperScan("com.mybasicplus.mapper")
public class DemoApplication {

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

}

6. Test

@SpringBootTest
class DemoApplicationTests {
    @Resource
    private EmpMapper empMapper;

    @Test
    public void contextLoads() {
        //System.out.println("--------- selectAll method test -----");
        User user=empMapper.selectById(2);
        System.out.println(user);
        //Assert.assertEquals(5,userList.size());
        //userList.forEach(System.out::println);
    }

4. crud operation

(1) Add insert

entry entity

@Data
@TableName(value = "tab_user")
@NoArgsConstructor
/*@AllArgsConstructor*/
public class User {
    @TableId(value = "id",type = IdType.ASSIGN_ID )
    private Long id;
    //@TableField(value = "name")
    private String name;
    //@TableField(value = "age")
    private Integer age;
    //@TableField(value = "email")
    private String email;

test

/**
     * If you do not want to use the id generated by the snowflake algorithm, you can specify the generation strategy of the primary key yourself
     */
    @Test
    public void testInsert(){
       User user=new User(null,"James",12,"111@aa.com",);//1406790199747428353: distributed id generation strategy for snowflake algorithm
        int row = userMapper.insert(user);
        System.out.println(row);
    }

(2) Delete delete

Logical deletion:

explain:

Only works for automatically injected sql:

Insert: no restrictions
Find: append the where condition to filter out the deleted data, and use wrapper The where condition generated by entity ignores this field
Update: append a where condition to prevent updating to deleted data, and use wrapper The where condition generated by entity ignores this field
Delete: convert to update

Add a logical field to the table

@Data
@TableName(value = "tab_user")
@NoArgsConstructor
/*@AllArgsConstructor*/
public class User {
    @TableId(value = "id",type = IdType.ASSIGN_ID )
    private Long id;
    //@TableField(value = "name")
    private String name;
    //@TableField(value = "age")
    private Integer age;
    //@TableField(value = "email")
    private String email;

    @TableLogic
    private Integer deleted;

Test:

  /**
     * Logical deletion:
     */
    @Test
    public void testDelete(){
        int i = userMapper.deleteById(2);
        System.out.println(i);
    }

(3) Modify update

Auto fill:

(1) Add the following comments to the corresponding attribute fields

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

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

(2) Create an autoconfiguration class

@Configuration //Indicates that this class is a configuration class
public class MybatisPlusConfig  implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        /**
         * Which field is auto populated for
         */
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date()); // Starting version 3.3.0 (recommended)
        this.strictInsertFill(metaObject, "updateTime", Date.class, new Date()); // Starting version 3.3.0 (recommended)
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date()); // Starting version 3.3.0 (recommended)
    }
}

(3) Testing

@Test
    public void testInsert(){

        User user=new User(null,"James",12,"111@aa.com",0);
        int row= empMapper.insert(user);
        System.out.println(row);
    }


    @Test
    public  void  testDelete(){
        int i = empMapper.deleteById(2);
        System.out.println(i);
    }

    @Test
    public void testUpdate(){
        /*User user=new User(2L,"wangwu",11,"120@qq.com",0);*/
        User user=new User(2L,"yu",12,"yyy",0);
        int i=empMapper.updateById(user);
    }

(4) Query --- condition query

 @Test
    public void testSelectBycondication(){
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.between("age",10,12);
        wrapper.or();
        wrapper.like("name","Zhan");
        wrapper.orderByDesc("age");
        List<User> users=empMapper.selectList(wrapper);
        System.out.println(users);
    }

(5) Paging query

1. Introduce paging plug-in

 @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

2. Use paging method

 @Test
    public void testSelectByPage(){
        Page<User> page=new Page<>(3,4);
        Page<User> page1=empMapper.selectPage(page,null);
        System.out.println("Total page:"+page1.getPages());
        System.out.println("Total number of articles:"+page1.getTotal());
        System.out.println("Current page record"+page1.getRecords());
    }

 

Keywords: Mybatis

Added by amax on Fri, 28 Jan 2022 01:21:46 +0200