I heard that wechat search “Java fish” will change strong oh!

This article is posted on Github and Gitee, and contains my entire Java series of articles for study and interview purposes

(1) Preface

When JDBC was first written, connection information was manually configured and SQL statements were written by hand. Later Mybatis appeared, there is no need to manually configure the connection information, SQL statements and code isolated, but still have to write SQL. Then came MybatisPlus, where you didn’t even have to write Sql.

(b) What is MybatisPlus

First of all, take out the official website address:

mp.baomidou.com/guide/

In brief, MybatisPlus is an enhanced tool of Mybatis, which simplifies development and improves development efficiency. In the official website, he used such a picture to show the relationship between MybatisPlus and Mybatis.

In the picture, MybatisPlus says that the relationship between Mybatis and MybatisPlus is like that of two brothers in Contra, they don’t affect each other, but they help you fight monsters more easily.

(3) Pre-preparation

Before we talk about MybatisPlus, let’s prepare a batch of data

CREATE DATABASE user;
USE user;
SET NAMES utf8mb4;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT 'user Id',
  `username` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT 'Username',
  `password` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT 'password',
  `gmt_create` datetime(3) NOT NULL COMMENT 'Creation time',
  `gmt_modified` datetime(3) NOT NULL  COMMENT 'Modification time'.PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci;
INSERT INTO `user` VALUES
(1.'a001'.'name1'.'123456',now(),now()),
(2.'a002'.'name2'.'123456',now(),now()),
(3.'a003'.'name3'.'123456',now(),now()),
(4.'a004'.'name4'.'123456',now(),now()),
(5.'a005'.'name5'.'123456',now(),now()),
(6.'a006'.'name6'.'123456',now(),now()),
(7.'a007'.'name7'.'123456',now(),now()),
(8.'a008'.'name8'.'123456',now(),now()),
(9.'a009'.'name9'.'123456',now(),now()),
(10.'a010'.'name10'.'123456',now(),now())
Copy the code

(4) Mybatis quick start

1. Introduce the latest dependencies

<dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>Latest Version</version>
</dependency>
Copy the code

2. Configure the database connection information in the configuration center

spring.datasource.url=JDBC: mysql: / / 192.168.61.102:3306 / user? serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
Copy the code

3. Add the MapperScan annotation to the Spring startup class

@SpringBootApplication
@MapperScan("com.example.mybatisplus.mapper")
public class MybatisPlusApplication {
    public static void main(String[] args) { SpringApplication.run(MybatisPlusApplication.class, args); }}Copy the code

Create mapper, DO

MybatisPlus can automatically generate Mapper, DO, Service, Controller. The first difference between MybatisPlus and Mybatis is that the @tablename annotation is used to indicate which table the current entity class corresponds to

@Data
@TableName("user")
public class UserDO {
    private Long id;
    private String userId;
    private String username;
    private String password;
    private LocalDateTime gmtCreate;
    private LocalDateTime gmtModified;
}
Copy the code

When you create the Mapper class, you inherit the BaseMapper class, which is a base class provided by MybatisPlus that encapsulates common query operations

public interface UserMapper extends BaseMapper<UserDO> {}Copy the code

5. Query data

When using Mybatis, data CRUD can only be realized by writing SQL. BaseMapper provided by MybatisPlus provides both Mapper level encapsulation interface and Service level encapsulation interface. Based on the previous writing method, the usual development will be more inclined to use the Mapper level interface introduction Mapper level several interfaces:

For example, if I want to query the amount of data in the user table, I can directly call:

Integer integer = userMapper.selectCount(null);
Copy the code

MybatisPlus provides a conditional constructor, Wrappers, with which you can construct a series of conditions, such as querying data with username name1

List<UserDO> userDOList = userMapper.selectList(Wrappers.<UserDO>lambdaQuery()
                .eq(UserDO::getUsername, "name1"));
Copy the code

Or let’s say I want to query for data whose ID is greater than 5

List<UserDO> userDOList1 = userMapper.selectList(Wrappers.<UserDO>lambdaQuery()
                .gt(UserDO::getId, 5));
Copy the code

6. Data insertion

We can set the primary key increment method with an @tableID annotation. We can set the data auto-fill method with the @TableField annotation. So modify the UserDO class:

@Data
@TableName("user")
public class UserDO {
    @TableId(type = IdType.AUTO)
    private Long id;
    private String userId;
    private String username;
    private String password;
    @TableField(fill = FieldFill.INSERT)
    private LocalDateTime gmtCreate;
    @TableField(fill = FieldFill.INSERT_UPDATE)
    private LocalDateTime gmtModified;
}
Copy the code

In the entity class, set the ID increment, set gmtCreate to fill in automatically when it is inserted, set gmtModified to fill in automatically when it is created and modified, and then configure the autofill rule:

@Configuration
public class MybatisObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        setFieldValByName("gmtCreate", LocalDateTime.now(),metaObject);
        setFieldValByName("gmtModified", LocalDateTime.now(),metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        setFieldValByName("gmtModified",LocalDateTime.now(),metaObject); }}Copy the code

Finally, call the API directly to insert the data

@Test
public void test3(a){
    UserDO userDO=new UserDO();
    userDO.setUserId("a011");
    userDO.setUsername("name11");
    userDO.setPassword("123456");
    userMapper.insert(userDO);
}
Copy the code

More query methods can refer to the official website, very detailed. However, if your SQL involves multiple table join operations, or you can write your own SQL as MyBatis.

(5) Summary

At this point, you should have a general understanding of MybatisPlus, it is also worth mentioning that MybatisPlus open source organization Is a domestic organization, so this document is especially friendly for domestic developers, can be used at ease. I’m fish boy. See you next time!