1. Introduce mybatis plus
Mybatis plus is only an enhancement tool of mybatis. Based on mybatis, it is only enhanced without change. It is developed for simplification and efficiency improvement. Mybatis plus is only applicable to single tables, and multiple tables must use mybatis
2. Characteristics of mybatis plus
No invasion
: only enhance without change, and the introduction of it will not affect the existing project, which is as smooth as silk
Low loss
Basic startup will automatically inject:
CURD
, basically no performance loss, direct object-oriented operation
Powerful
CRUD
operation
: built in universal
Mapper
. general
Service
, most single tables can be realized only through a few configurations
CRUD
exercise
More powerful condition constructor to meet all kinds of use needs
support
Lambda
Formal call
: passed
Lambda
Expression, convenient to write all kinds of query conditions, and there is no need to worry about wrong fields
JDK1.
Support automatic generation of primary key
: up to
4
Primary key policy (including distributed unique key)
ID
generator
- Sequence
), freely configurable, perfect
Solve the primary key problem
support
ActiveRecord
pattern
: support
ActiveRecord
Formal call, entity class only needs to inherit
Model
Class for powerful
CRUD
operation
Supports custom global general operations
: support global common method injection(
Write once, use anywhere
)
Built in code generator
: use code or
Maven
Plug ins can be generated quickly
Mapper
,
Model
,
Service
,
Controller
Layer generation
Code, support template engine, and more custom configurations are waiting for you to use
Built in paging plug-in
: Based on
MyBatis
For physical paging, developers do not need to care about specific operations. After configuring the plug-in, writing paging is equivalent to ordinary paging
List
query
The paging plug-in supports multiple databases
: support
MySQL
,
MariaDB
,
Oracle
,
DB2
,
H2
,
HSQL
,
SQLite
,
Postgre
,
SQLServer
And other databases
Built in performance analysis plug-in
: exportable
Sql
Statement and its execution time. It is recommended to enable this function when developing and testing, which can quickly find out slow queries
Built in global interception plug-in
: provide full table
delete
,
update
Operate intelligent analysis blocking, or customize interception rules, pre
3. Use of mybatis plus
3.1 in POM Introducing dependency into XML
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.1</version> </dependency>
3.2 configuration file application Properties (connect to database)
spring.datasource.username=root spring.datasource.password= spring.datasource.url=jdbc:mysql://localhost:3306/mybatisplus?serverTimezone=Asia/Shanghai spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
3.3 create an entity class (the parameter type shall be written as the packaging class of eight basic data types as far as possible)
The reasons for writing packaging are as follows:
1. Prevent null pointer exception
2. If the wrapper class cannot receive the parameter, it will prompt null, and the basic data type will not prompt
package com.thm.mybatisplus.mybatisplus.entry; import com.baomidou.mybatisplus.annotation.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Date; @Data//Get get set method @AllArgsConstructor//Parametric structure @NoArgsConstructor//Nonparametric structure public class User { /* @TableId(type= IdType.ASSIGN_ID)*///Snowflakes automatically generate primary keys @TableId(type= IdType.AUTO)//The primary key in the database must be auto incremented*/ private Long id; /*Used when the column name is inconsistent with the attribute name * @TableFiled(value="u-name") * Annotate the field names in the declaration database * */ private String name; private Integer age; private String email; @TableLogic//Delete comments logically private Integer deleted; public User(Long id, String name, Integer age, String email, Integer deleted) { this.id = id; this.name = name; this.age = age; this.email = email; this.deleted = deleted; } public User(String name, Integer age, String email, Integer deleted) { this.name = name; this.age = age; this.email = email; this.deleted = deleted; } @TableField(fill = FieldFill.INSERT)//Auto fill in time when adding private Date createTime; @TableField(fill = FieldFill.INSERT_UPDATE)//Auto fill time when modifying private Date updateTime; }
4. Interface mapper
Create an interface and inherit BaseMapper
5. Add package scanning annotation in active class
6. Write in the test class, query according to ID and query all
7. Add insert (written in test class)
/*newly added*/ @Test public void testinsert(){ /* User user=new User(null,"Wang Wuwu, "15,"234@qq.com",0);*///snowflake User user=new User("Zhang San",12,"234@qq.com",0);//No, the primary key in the database must be incremented automatically*/ int i=userMapper.insert(user); System.out.println(i); }
8. Delete (logical deletion is based on the ID. after deletion, it cannot be queried, but the records still exist in the database)
First, add a field in the database
Add the following annotations and fields to the entity class
The code written in the test class is as follows
/* * Logical deletion*/ @Test public void testdelete(){ int i=userMapper.deleteById(1); System.out.println(i); }
9. Modify update
To automatically fill in time, first create a configuration class with the following code
Add two fields to the database
Add two attributes to the entity class
@TableField(fill = FieldFill.INSERT)//Auto fill in time when adding private Date createTime; @TableField(fill = FieldFill.INSERT_UPDATE)//Auto fill time when modifying private Date updateTime;
The code in the test class is as follows
/*modify*/ @Test public void testupdate(){ User user=new User(140688314676011008L,"Zhang San",16,"1111@qq.com",0); int i=userMapper.updateById(user); System.out.println(i); }
10. Query - query by criteria
/* * Condition query * */ @Test public void testSelectByCondication(){ // Wrapper: conditional wrapper class QueryWrapper<User> wrapper=new QueryWrapper<>(); wrapper.between("age",10,19); wrapper.or(); wrapper.like("name","Small"); List<User> list=userMapper.selectList(wrapper); System.out.println(list); }
11. Paging query
The paging plug-in needs to be introduced into the configuration class
@Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return interceptor; }
Test class
/* The first step is to configure the paging plug-in * Query pagination displays the current page number and the current number of pages * */ @Test public void testSelectByPage(){ Page<User> page=new Page<>(2,4); Page<User> page1=userMapper.selectPage(page,null); System.out.println("Current total page number:"+page1.getPages()); System.out.println("Total number of articles:"+page1.getTotal()); System.out.println("Record of current page:"+page1.getRecords()); }