编程知识 cdmana.com

After using mybatisplus, I haven't written SQL for a long time

I heard that wechat search 《Java Young fish 》 It's going to change !

This article is included in github and gitee , There's my whole Java Series articles , Study or interview can see oh

( One ) Preface

First write JDBC When , To manually configure the connection information , Write one by one sql sentence . later Mybatis There is , There is no need to manually configure the connection information ,sql Statements are also isolated from code , But I have to write Sql. Then there was MybatisPlus, This next company Sql No need to write .

( Two ) What is? MybatisPlus

First, take out the official website address :

mp.baomidou.com/guide/

simply ,MybatisPlus yes Mybatis Enhanced tools for , Simplify the development , Improve development efficiency . In the website , He used such a picture to show MybatisPlus and Mybatis The relationship between .

In the picture ,MybatisPlus Indicates that it and Mybatis The relationship between them is like two brothers in a soul fight , They don't affect each other , But it can make it easier for you to fight monsters .

( 3、 ... and ) Lead to

In the interpretation of the MybatisPlus Before , Let's prepare a batch of data first

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 ' user name ',
  `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 code 

( Four )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 code 

2、 Configure 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 code 

3、 stay Spring Add in startup class MapperScan annotation

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

4、 establish mapper,DO

MybatisPlus Can be generated automatically Mapper、DO、Service、Controller, Here's a tutorial , Manual establishment .MybatisPlus and Mybatis The first difference , Use here @TableName The annotation indicates 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 code 

establish Mapper Class time , Inherit BaseMapper class , This is a MybatisPlus Provides a base class , Encapsulates common query operations

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

5、 Query data

In the use of Mybatis when , Data CRUD All need to be written sql Can achieve ,MybatisPlus Provided BaseMapper Both provide Mapper Layer encapsulation interface , And provides Service Layer encapsulation interface . Based on the previous writing , In normal development, we tend to use Mapper The interface of the layer Introduce Mapper Several interfaces at the level :

For example, I want to inquire user The amount of data in the table , I can call :

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

MybatisPlus Provides a condition constructor Wrappers, Can pass Wrappers Construct a series of conditions , Such as query username by name1 The data of

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

Another example is that I want to query id Greater than 5 The data of

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

6、 Insert data into

There is no problem using the above method for data query , There are several things you can optimize when inserting data , We can use an annotation @TableId Set the auto increment method of the primary key , Can pass @TableField Annotation sets the automatic filling of data . So modify UserDO This 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 code 

In entity classes , Set up id Self increasing , Set up gmtCreate Auto fill on insert , Set up gmtModified Automatically fill in when creating and modifying , Then configure auto fill rules :

@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 code 

Finally, call API insert data

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

For more query methods, please refer to the official website , Very detailed . But if yours sql The operation of connecting tables involving multiple tables , You can still talk to yourself MyBatis Same handwriting sql.

( 5、 ... and ) summary

thus , You should be right. MybatisPlus Have a general understanding of , Another thing worth mentioning MybatisPlus The open source organization Baomi bean is a domestic organization , Therefore, this document is particularly friendly to domestic developers , Safe to use . I'm a fish , See you next time !

版权声明
本文为[Java fish]所创,转载请带上原文链接,感谢
https://cdmana.com/2021/09/20210909124112659r.html

Scroll to Top