Mybatis plugs Development Manual

Mybatis plugs is designed to simplify code

mybatis enhancement Kit



[August 2022]

[a breeze]


1. Introduction 1

1.1 introduction 1

1.2 purpose 1

1.3 characteristics 1

2. Quick start 1

2.1 create table 1

2.2 create springboot project 1

2.3 configure maven 3

2.4 configuring yml 4

2.4 modify startup class 5

3. Code generator 5

3.1 configuration code generator 5

3.2 use method 6

3.3 create code package 7

3.4 copy code 8

3.5 start item 8

4. CRUD interface 8

4.1 plug in interface 9

4.1.1 single insertion 9

4.1.2 batch insertion9

4.2 deleting interface 10

4.2.1 single deletion 10

4.2.2 batch deletion 11

4.3 modifying interface 11

4.3.1 single modification 11

4.3.2 batch modification12

4.4 list query interface 13

4.5 paging query 14

4.6 query list 15

4.7 query quantity 15

5. Conditional constructor Wrapper 16

5.1 eq construction 16

5.2 ne structure 16

5.3 like structure 16

5.4 in construction 17

6. Login authentication 17

6.1 creating JWT 17

6.2 analysis of JWT 20

6.3 encapsulating login entity 21

7. Interceptor 21

7.1 introduction 21

7.2 intercept request 23

7.3 release request 23

8. Enumeration conversion 24

8.1 defining enumeration classes 24

8.2 entity class reference enumeration 26

8.3 adding configuration files 26


  1. introduce


Mybatis plugs is an enhanced persistence layer framework developed based on mybatis.

Just introduce the dependency mybatis plug-ins spring boot starter in the springboot project

You can simplify the CRUD operation of mybatis without writing the basic addition, deletion, modification and query sql.

1.2 purpose

Mybatis plug is designed to simplify code.

1.3 characteristics

Do not make any changes to mybatis, only do the expansion and enhancement of mybatis.

The code is automatically generated. According to the table name, the files of,,, and xxxMapper.xml can be quickly generated.

Less dependence, only relying on mybatis plug-spring-boot-starter

Automatically fill in the creation time, update time, creator and other information.

Built in paging plug-in based on Mybatis physical paging.

Automatically record the execution time of sql to facilitate locating slow queries.

The code is simple and easy to understand.

The built-in interface interceptor determines whether to intercept requests through annotations.

  1. Quick start

We will explain the powerful functions of mybatis plugs through a simple Demo. Before that, we assume that you have:

a. Have Java development environment, corresponding IDE and mysql database

b. Familiar with Spring Boot

c. Familiar with Maven

What do we need to do if we use mybatis plugs to add, delete, modify and check the table from scratch?

2.1 create table

There is an existing sys_user table, and the corresponding database Sql script is as follows:

CREATE TABLE sys_user ( id bigint NOT NULL COMMENT 'Primary key ID', name varchar(30) COMMENT 'full name', age int COMMENT 'Age', phone varchar(11) COMMENT 'Telephone', PRIMARY KEY (id))

2.2 create springboot project

Create a SpringBoot project using idea

Step 1:

Step 2:

Step 3: select LomBok plug-in

Basic structure of the project

2.3 configure maven

After the springBoot project is established, add the dependency of mybatis plug in the pom.xml file


Current latest version: mybatis plugs spring boot starter

<dependency>  <groupId>com.enbatis</groupId>  <artifactId>mybatis-plugs-spring-boot-starter</artifactId>  <version>Current latest version</version></dependency>


After introducing mybatis plug-ins spring boot starter, there is no need to introduce mybatis again

2.4 configuring yml

Modify to application.yml

New development environment: application-dev.yml

New test environment: application-test.yml

New production environment: application-pro.yml

Novel Ming

1. The development environment is the configuration we use for development

2. The test environment is the configuration used by testers for software testing

3. Configuration of production environment for online deployment


spring:  profiles:    active: devserver:  port: 8080


spring:  profiles:    active: dev

Specify the environment to use


Specify that the port started by the project is port 8080


2.4 modify startup class

Annotate Mapper scan on the startup class


3. Code generator

We can quickly generate through database tables


The code generation needs to connect to the database, so we need to connect to the database. We only need to configure the basic information of the database and generate the class CodeGenerator2 by using the code of mybatis plug

3.1 configuration code generator

Create the generator class CodeGenerate under the same level directory of the startup class

import com.enbatis.mybatisplugs.generate.CodeGenerator2; public class CodeGenerate {   private static String url="jdbc:mysql:// useUnicode=true&characterEncoding=utf8&useSSL=false";    private static String user="root";    private static String psd="111111";    private static String filePath="D://generate_code//";    public static void main(String[] args) {     CodeGenerator2 codeGenerator2=new CodeGenerator2(url,user,psd,filePath);     codeGenerator2.generate(CodeGenerate.class);   } } 


url: database connection url

root: database user name

psd: database password

filePath: java code generation location (to prevent code overwriting, we will not automatically generate to the corresponding code location)

CodeGenerator2: mybatis plug code core generator

3.2 use method

  1. Execute the main method

  2. In the console, enter the author and the table to generate the code

  1. After entering, click enter

  2. When the following information is output, the code generation is successful

  1. Go to the code generation location to view the generated code

3.3 create code package

Create folders for code packages: entity, controller, mapper, service, impl and xml

3.4 copy code

Copy the generated code to the corresponding folder

3.5 startup project

Start project access http://localhost:8080/v1/sys_user/list Query all users list

4. CRUD interface

Note: by encapsulating the BaseService interface of mybatis, the CRUD operation of the database can be quickly realized

Generic T is any entity object; The parameter Serializable is any type of primary key mybatis plugs does not recommend using a composite primary key convention. Each table has its own unique id primary key; The object Wrapper is a conditional constructor.

4.1 plug in interface

4.1.1 single insertion


*Insert a record

*@ param entity incoming Insert Object

* @return T


T insert(T entity);

Usage: write code in the serviceImpl layer as follows

SysUser user = new SysUser();user.setName("Zhang San");user.setAge(32);user.setPhone("13615425135");super.insert(user);

4.1.2 batch insertion


*Batch insert

* @param entityList

* @return


int saveBatch(List<T> entityList);

Usage: write code in the serviceImpl layer as follows

List<SysUser> sysUserList = new ArrayList<>();for (int i = 0; i <10 ; i++) {SysUser sysUser = new SysUser();sysUser.setName("Zhang San"+i);sysUser.setAge(30+i);sysUser.setPhone("1361542513"+i);sysUserList.add(sysUser);}super.saveBatch(sysUserList);

4.2 deleting an interface

4.2.1 single deletion


*Delete a piece of data according to id

*@ param ID: query ID passed in

*@ return "number of deleted items"


int deleteById(Serializable id);

Usage: write code in the serviceImpl layer as follows


4.2.2 batch deletion


*Batch delete

* @param wrapper

* @return


int delete(Wrapper<T> wrapper);

Usage: write code in the serviceImpl layer as follows

Wrapper wrapper = new Wrapper<SysUser>();wrapper.eq("age",30);"name","Zhang San");super.delete(wrapper);

Note: the conditional constructor will be specially explained.

4.3 modify interface

4.3.1 single modification


*Update a piece of data according to id

*Update object passed in by @ param bean

*@ return "returns the number of updates."


int updateById(T bean);

Usage: write code in the serviceImpl layer as follows

SysUser sysUser = new SysUser();sysUser.setId(1234561114L);sysUser.setPhone("13615425135");sysUser.setAge(36);super.updateById(sysUser);

4.3.2 batch modification


*Batch modification

* @param entityList

* @return


int updateBatchById(List<T> entityList);

Usage: write code in the serviceImpl layer as follows

List<SysUser> sysUserList = new ArrayList<>();SysUser sysUser = new SysUser();sysUser.setId(111100001101L);sysUser.setAge(35);sysUserList.add(sysUser);SysUser sysUser2 = new SysUser();sysUser2.setId(111100001102L);sysUser2.setAge(32);sysUserList.add(sysUser);super.updateBatchById(sysUserList);

4.4 list query interface


*Query list data

*@ param wrapper query criteria

*@ return "collection"


List<T> list(Wrapper<T> wrapper);

Usage: write code in the serviceImpl layer as follows

Wrapper wrapper = new Wrapper<SysUser>();"name","Zhang San");List<SysUser> list = super.list(wrapper);

4.5 paging query


*Paging query

* @param page

* @param wrapper

* @return


Page<T> page(Page<T> page, Wrapper<T> wrapper);

Usage: write code in the controller layer as follows

@PostMapping("/page")public ResultReturn<Page<SysUser>> getPage(@RequestBody SysUser user){return success( getPage(),new Wrapper(user)));}

Note: controller needs to inherit BaseController

4.6 single query


*Get by id

*@ param ID object ID

*@ return object


T getById(Serializable id);

Usage: write code in the controller layer as follows

@GetMapping("/{id}")public ResultReturn<SysUser> get(@PathVariable("id") Long id) {return success(sysUserService.getById(id));}

4.7 query quantity


*Query count

*@ param wrapper query criteria

*@ return "quantity"


int selectCount(Wrapper<T> wrapper);

Usage: write code in the serviceImpl layer as follows

Wrapper wrapper = new Wrapper<SysUser>();"name","Zhang San");int count = super.selectCount(wrapper);

5. Conditional constructor Wrapper

5.1 eq construction

If we want to quickly query the database table sys_ How to operate when the user's name is "Tom"?

Answer: just call the service to call the list, pass in the condition constructor Wrapper, and the Wrapper calls the eq method. The following method is to query the SysUser list whose name is Tom

sysUserService.list(new Wrapper<>(sysUser).eq("name","Tom"));

5.2 ne structure

If we want to quickly query the database table sys_ How to operate if the user's name is not "Tom"?

Answer: just call the service to call the list, pass in the condition constructor Wrapper, and the Wrapper calls the ne method. The following method is to query the SysUser list whose name is not Tom

sysUserService.list(new Wrapper<>(sysUser).ne("name","Tom"));

5.3 like structure

If we want to fuzzy query by name, how do we do it?

Answer: just call the list to pass in the condition constructor Wrapper, and the Wrapper calls the like method. The following method is a fuzzy query based on the name "Tom"

sysUserService.list(new Wrapper<>(sysUser).like("name","Tom"));

5.4 in construction

If we want to query the names of "Tom", "Jack" and "June", how do we operate?

Answer: just call the service to pass in the condition constructor Wrapper and the Wrapper to call the in method to pass in the ArrayList

List arrayList=new ArrayList<>(); arrayList.add("Tom"); arrayList.add("Jack"); arrayList.add("June");sysUserService.list(new Wrapper<>(sysUser).in("name",arrayList));


The above only lists the methods of some conditional constructors. We also have notNull (non null query), isNull (null value query), setSqlSelect (fixed column query), and so on. For more information, please check mybatis plugs

6. Login authentication

Mybatis plugs internally encapsulates JWT token authentication, which can be used directly when performing login function.

6.1 create JWT

Mybatis plugs provides JwtUtil tool classes to create token s. The specific methods are as follows:

/*** The first three parameters are some information of the user token, such as id, permission, name, etc. Don't put private information into (everyone can get) * @ param map information to be encrypted * @ param security encryption string * @ param expire expiration time in milliseconds * @ return*/public static String createJwt(Map<String,Object> map,String security,long expire) {//Add the parameter jwtbuilder builder = jwts. Builder() setHeaderParam("typ", "JWT"). setIssuedAt(new Date()). setExpiration(new Date(System.currentTimeMillis()+expire)).setClaims(map).signWith(generalKey(security),SignatureAlgorithm. HS256);// Generate JWTreturn builder.compact();}

If the failure time is not transmitted, it will default to 24 hours. We provide an overloaded method

/*** Create JWT. The default expiration time is 24 hours. * @ param map information to be encrypted * @ param base64Security encryption string * @ return*/public static String createJwt(Map<String, Object> map, String base64Security) {return createJwt(map,base64Security,EXPIRE);}

How to use it? Please refer to the following code:

//Get login user name

String username =user.getUsername();String password= MD5Util.generate(user.getPassword());List<SysUser> list=list(new Wrapper().eq("username",username).eq("password",password));Optional<SysUser> first=>dbUser.getUsername().equals(username)&&dbUser.getPassword().equals(password)).findFirst();if (first.isPresent()){user.setUsername(username);SysUser sysUser= first.get();Map<String,Object> userMap = new HashMap<>();userMap.put("userId",sysUser.getId()+"");userMap.put("name",sysUser.getName());userMap.put("companyId",sysUser.getCompanyId());userMap.put("username",sysUser.getUsername());userMap.put("effective", System.currentTimeMillis()+(120*60*1000));String token= JwtUtil.createJwt(userMap, JwtUtil.LOGIN_BASE);response.addHeader("authorization",token);Cookie cookie = new Cookie("authorization",token);cookie.setDomain(domain);cookie.setPath("/");response.addCookie(cookie);SysUser user1= first.get();SysUserVO vo = new SysUserVO();BeanUtils.copyProperties(user1,vo);vo.setAuthorization(token);vo.setImgHead(sysUser.getAvatarUrl());return  ResultReturn.success(vo);}

6.2 parsing JWT

Mybatis plugs provides JwtUtil tool class to parse token s. The specific methods are as follows:

/*** Decryption * @ param jsonWebToken token string * @ param security encrypted string * @ return*/public static Claims parseJwt(String jsonWebToken, String security) {try {Jws<Claims> claimsJws = Jwts.parserBuilder().setSigningKey(Keys.hmacShaKeyFor(security.getBytes(StandardCharsets.UTF_8))).build().parseClaimsJws(jsonWebToken);return claimsJws.getBody();} catch (Exception ex) {ex.printStackTrace();return null;}}

6.3 package login entity

After successful login, you can use the token to obtain the Account of the login entity to obtain the login user. The specific method is as follows:

public static Account account(String token,String security){Claims claims= JwtUtil.parseJwt(token,security);String userId= (String)claims.get("userId");String username= (String)claims.get("username");Integer companyId= (Integer)claims.get("companyId");Account account = new Account();account.setId(Long.parseLong(userId));account.setUsername(username);if(null!=companyId){account.setCompanyId(Long.parseLong(Integer.toString(companyId)));}return account;}

Where token is the token generated by jwt, security is the encrypted string, and the token can be obtained from the head or cookie.

See the following codes for specific usage:

Account account = JwtUtil.account(request.getHeader("Authorization"),"xxxx");

7. Interceptor

7.1 introduction

The interceptor of mybatis plugs has the functions of recording the execution time of the request method and filtering the requests of non login users. You can use annotations in the controller to intercept the non login requests.

usage method:

Customize interceptors and inherit classes:


The example code is as follows:

@Componentpublic class ReqInterceptor extends Interceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{return super.preHandle(request,response,handler);}}

Next, register the interceptor, create a new class WebConfigurer and implement the WebMvcConfigurer interface. The code is as follows:

@Configurationpublic class WebConfigurer implements WebMvcConfigurer {@Autowiredprivate ReqInterceptor interceptor;/*** @Description  This method is used to configure static resources, such as html, js, css, etc. * @ Param [registry]* @return void**/@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {}/*** @Description  This method is used to register the interceptor. The interceptor written by us needs to be registered here to take effect * @ Date 9:34 2022/2/7* @Param [registry]* @return void**/@Overridepublic void addInterceptors(InterceptorRegistry registry) {// addPathPatterns("/ * *") means to intercept all requests. registry.addInterceptor(interceptor).addPathPatterns("/ * *");}}

After configuration, the function of mybatis plugs interceptor can be realized.

7.2 interception request

The Controller method can intercept requests without any annotation or annotation @ Login(handler = Handler.INTERCEPT). If the user accesses the interface without logging in, the system will throw the information of not logging in.

7.3 release request

Some requests can be accessed directly without login, such as registration interface, login interface, etc. at this time, the @ Login(handler = Handler.PASS) annotation can be used to release the request, that is, access can be accessed without login. The code example is as follows:

Registration interface:

@Login(handler = Handler.PASS)@PostMapping("/register")public ResultReturn registerUser(@RequestBody SysUserVO sysUser){sysUser.setCompanyId(0L);return  sysUserService.registerUser(sysUser);}

Login interface:

@Login(handler = Handler.PASS)@PostMapping("/login")public ResultReturn login(@RequestBody SysUserVO vo){return  sysUserService.login(vo,request,response);}

8. Enumeration conversion

Sometimes the database stores numeric types, but we need to use enumeration classes in entity classes. In this case, mybatils plugs provides a convenient and fast way to meet the requirements.

8.1 defining enumeration classes

First, customize the enumeration class and implement the com.enbatis.mybatisplugs.enums.BaseEnum interface. The code is as follows:

import com.enbatis.mybatisplugs.enums.BaseEnum;public enum StatusEnum implements BaseEnum<StatusEnum,Integer> {    ORDERED(0,"Order placed"),    PAYED(1,"Paid"),    DELIVER(2,"Consignment"),    DELIVERED(3,"Shipped"),    RECEIVED(4,"Received goods"),    OK(5,"Order completion");
    private final Integer value;    private final String description;
    StatusEnum(Integer value, String description) {        this.value = value;        this.description = description;    }    public StatusEnum getEnumByValue(Long value) {        StatusEnum[] enums = StatusEnum.values();        for (StatusEnum e : enums) {            if (e.getValue().equals(value)) {                return e;            }        }        return null;    }    @Override    public Integer getValue() {        return value;    }
    @Override    public String getDescription() {        return description;    }}

8.2 entity class reference enumeration

You need to change the field to enumeration type in the entity class, as follows:

/*** Order status(*/private StatusEnum status;

8.3 add configuration file

You need to add a class for enumeration conversion in the configuration file:


The code is as follows:

mybatis:  mapper-locations: classpath:/mapping/*.xml  type-aliases-package: com.panpan.housesale.entity  configuration:    map-underscore-to-camel-case: true    #log-impl: org.apache.ibatis.logging.stdout.StdOutImpl    default-enum-type-handler: com.enbatis.mybatisplugs.plugin.parser.AutoEnumTypeHandler

Through these three steps, you can match the database field type with the enumeration type.

Tags: Java Spring Boot Mybatis

Posted by echelon2010 on Thu, 25 Aug 2022 06:49:47 +0530