(1) Preface
When you first wrote JDBC, you needed to manually configure connection information by writing SQL statements one by one. Then Mybatis appeared, no more manual configuration of connection information was needed, and the SQL statements were isolated from the code, but Sql was unavoidable. Then Mybatis Plus appeared, which did not even require Sql to be written.
(2) What is MybatisPlus
First, take out the official website address:
https://mp.baomidou.com/guide/
Simply put, MybatisPlus is an enhanced tool for Mybatis to simplify development and increase efficiency. On the official website, he uses this chart to show the relationship between MybatisPlus and Mybatatis.
In the picture, Mybatis Plus indicates that the relationship between Mybatis Plus and Mybatatis is like two brothers in a fight. They don't affect each other, but they can help you make the odds easier.
(3) Pre-preparation
Before explaining 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 '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())
(4) Quick Start for Mybatis
1. Introduce the latest dependencies
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>Latest Version</version> </dependency>
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
3. Add MapperScan annotations 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); } }
4. Create mapper, DO
MybatisPlus automatically generates Mapper, DO, Service, Controller, which is created manually as a tutorial. The first difference between MybatisPlus and Mybatatis is that it uses the @TableName annotation 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; }
When creating a Mapper class, inherit the BaseMapper class, a base class provided by MybatisPlus that encapsulates common query operations
public interface UserMapper extends BaseMapper<UserDO> { }
5. Query Data
When using Mybatis, data CRUD s require sql to be implemented. BaseMapper provided by MybatisPlus provides both Mapper-level encapsulation interface and Service-level encapsulation interface. Based on previous writing, Mapper-level interface is more preferred in development.
Introduces several interfaces at the Mapper level:
For example, if I want to query the amount of data in the user table, I can call it directly:
Integer integer = userMapper.selectCount(null);
MybatisPlus provides a conditional constructor, Wrappers, that allows you to construct a series of conditions using Wrappers, such as querying data whose username is name1
List<UserDO> userDOList = userMapper.selectList(Wrappers.<UserDO>lambdaQuery() .eq(UserDO::getUsername, "name1"));
For example, I want to query data with id greater than 5
List<UserDO> userDOList1 = userMapper.selectList(Wrappers.<UserDO>lambdaQuery() .gt(UserDO::getId, 5));
6. Data insertion
There are several areas where you can optimize when inserting data. We can set the primary key auto-increment with a comment @TableId and the data auto-filling with the @TableField comment.
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; }
In the entity class, set the id to auto-increment, set gmtCreate to auto-fill at insert, set gmtModified to auto-fill at create and modify, and 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); } }
Last direct API call to insert data
@Test public void test3(){ UserDO userDO=new UserDO(); userDO.setUserId("a011"); userDO.setUsername("name11"); userDO.setPassword("123456"); userMapper.insert(userDO); }
More query methods can refer to the official website, which is very detailed. But if your sql involves joining multiple tables, you can still write sql yourself, just like MyBatis.
(5) Summary
At this point, you should have a general understanding of MybatisPlus. It is also worth mentioning that the open source organization of MybatisPlus, Brassica Beans, is a domestic organization, so this document is very friendly for domestic developers and safe to use. I am a fish and I will see you next time!