orm framework mybatis plus (Spring boot + Gradle installation and introduction) [2022]

Posted by dannymm on Fri, 04 Mar 2022 18:11:34 +0100


The reason for writing this article is that because the software version iterates too fast, many tutorials on the Internet are no longer appropriate, and many commands don't quite understand their meaning.

Official course


My version information

  • java 17.0.1 (later modified to 8, if there is any difference, it will be noted in the article)
  • gradle 7.4
  • mysql 8.0

Installation tutorial

  1. First, create a Spring boot (Gradle) project. The specific tutorial is the same as this introductory tutorial Portal agreement

  2. Installation related dependencies

Spring Boot



  • Open build gradle
compile group: 'com.baomidou', name: 'mybatis-plus-boot-starter', version: '3.5.1'
  • Since the new version cancels the use of compile, those that cannot run or report errors can be changed to the following
implementation group: 'com.baomidou', name: 'mybatis-plus-boot-starter', version: '3.5.1'

The version number version can be modified according to the official

Other configurations

dependencies {
	//SpringBoot basic configuration
	implementation 'org.springframework.boot:spring-boot-starter-web'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'

	//Mybatis plus (MP) dependency
	implementation group: 'com.baomidou', name: 'mybatis-plus-boot-starter', version: '3.5.1'

	//lombok java library dependency
	compileOnly 'org.projectlombok:lombok'
	annotationProcessor 'org.projectlombok:lombok'

	//devtool is used to configure hot deployment and can be deleted
	developmentOnly 'org.springframework.boot:spring-boot-devtools:2.6.3'

	//mysql database dependency
	runtimeOnly 'mysql:mysql-connector-java'

	testImplementation('org.springframework.boot:spring-boot-starter-test') {
		exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'


  • Then click Gradle on the right to refresh, as shown in the figure

  • Download successful

  • Configure MapperScan annotation (open the Application class). This is the configuration of Spring Boot. Please refer to the official document for the specific configuration of Spring
    How to fill in the address in MapperScan? I follow the com.com in the official tutorial baomidou. mybatisplus. samples. quickstart. Mapper then finds that it will report an error process' command 'C: / program files / Java / jdk-17.0.1/bin/java Exe '' finished with non zero exit value 1, so try to modify it according to the directory as follows (here I still use jdk17, but jdk8 will also report an error)

    If it can't be modified according to the directory, it can also be modified to com baomidou. mybatisplus. core. mapper

The solution to the mapper file not found in the directory (searched online, for reference only)

  • gradle will only regard the resource folder as a resource file by default. If your mapper file is placed in the java directory, it will not be entered into the compilation output directory after compilation,
  • Just. Build Add the following sourcesets to gradle main. resources. SRC dirs = ["Src / main / java", "Src / main / resources"] gradle will treat the java directory as a resource directory, and will output the mapper file to the directory after compilation
  • According to the update record of mybatis plus in 2022.1.1, Mapper related cache is added and removed, and GroovyClassLoader is supported to dynamically inject Mapper (ok...)
package com.example.demo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);


So far, the installation and configuration have been basically completed

@MapperScan specifies the path of the package of Mapper class to be scanned


Create a new package and a new User class

  • @TableName
    Description: a table name annotation that identifies the table corresponding to the entity class
    Use location: entity class
package com.example.demo.user;

import com.baomidou.mybatisplus.annotation.TableName;

public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;

  • @TableId
    Description: primary key annotation
    Usage location: entity class primary key field

  • More notes Teleporters

Add test dependency

Configure dependencies where they are installed

implementation group: 'com.baomidou', name: 'mybatis-plus-boot-starter-test', version: '3.5.1'



My build Gradle is as follows

plugins {
	id 'org.springframework.boot' version '2.6.4'
	id 'io.spring.dependency-management' version '1.0.11.RELEASE'
	id 'java'

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {

configurations {
	compileOnly {
		extendsFrom annotationProcessor


dependencies {
	//spring boot foundation dependency
	implementation 'org.springframework.boot:spring-boot-starter-web'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'

	//Mybatis plus dependency
	implementation group:'com.baomidou', name: 'mybatis-plus-boot-starter', version: '3.5.1'

	//lombok java library dependency
	compileOnly 'org.projectlombok:lombok'
	annotationProcessor 'org.projectlombok:lombok'

	//mysql database dependency
	runtimeOnly 'mysql:mysql-connector-java'

	testImplementation('org.springframework.boot:spring-boot-starter-test') {
		exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'

tasks.named('test') {

My application Properties are configured as follows


My database name is test, which can be modified according to my own database name
(in addition, if it is jdk8, you may need to add "serverTimezone=GMT%2B8" at the end, which is consistent with the above

Ensure that there is data in the database through visualization software

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;

import static org.assertj.core.api.Assertions.assertThat;

class MybatisPlusSampleTest {

    private SampleMapper sampleMapper;

    void testInsert() {
        Sample sample = new Sample();

Then implement the following and write the entity class user java,User. Content in Java class

import lombok.Data;

public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
  • The official documentation shows that using Lombok simplifies the code. If Lombok is not installed and downloaded, the declared class actually lacks some functions, such as set(), get(), and so on.

Then, you can directly use mybatis plus to let Usermapper inherit the interface of BaseMapper

package com.example.demo.user;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.stereotype.Repository;

public interface Usermapper extends BaseMapper<User> {


Add test classes for functional testing (according to official debugging)

package com.example.demo;

import com.example.demo.user.User;
import com.example.demo.user.Usermapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

class DemoApplicationTests {
	private Usermapper usermapper;

	void contextLoads() {
		List<User> user = usermapper.selectList(null);


Assert.assertEquals(); And its overload method:

  1. If the two are consistent, the program continues to run
  2. If the two are inconsistent, interrupt the test method and throw exception information

The function of @ MybatisPlusTest annotation is that we can start the modules we need to test without starting the whole database

  • It can be found in application Add in properties
#mybatis log

In this way, you can see the specific SQL and operations on the console

CRUD interface

  • The general Service CRUD encapsulates the IService interface and further encapsulates the CRUD. get is used to query the single line, remove is used to delete the list set, query the page page prefix, and the naming method is used to distinguish the Mapper layer to prevent confusion.


// Insert a record (select field, policy insert) entity object
boolean save(T entity);
// Insert (batch) entity object collection
boolean saveBatch(Collection<T> entityList);
// Insert (batch) insert batch quantity
boolean saveBatch(Collection<T> entityList, int batchSize);


// Delete records and entity objects according to entity conditions
boolean remove(Wrapper<T> queryWrapper);
// Delete and encapsulate operation classes according to ID and entity object
boolean removeById(Serializable id);
// Delete records, entity objects and collections according to columnMap conditions
boolean removeByMap(Map<String, Object> columnMap);
// Delete (batch delete according to ID), insert batch quantity
boolean removeByIds(Collection<? extends Serializable> idList);


// According to the UpdateWrapper condition, sqlset needs to be set for updating records
boolean update(Wrapper<T> updateWrapper);
// Update the record according to the whereWrapper condition
boolean update(T updateEntity, Wrapper<T> whereWrapper);
// Select modify according to ID
boolean updateById(T entity);
// Batch update by ID
boolean updateBatchById(Collection<T> entityList);
// Batch update by ID
boolean updateBatchById(Collection<T> entityList, int batchSize);


// Query by ID
T getById(Serializable id);
// Query a record according to Wrapper. If there are more than one result set, exceptions will be thrown. Take one randomly and add the limiting condition Wrapper last("LIMIT 1")
T getOne(Wrapper<T> queryWrapper);
// Query a record according to Wrapper
T getOne(Wrapper<T> queryWrapper, boolean throwEx);
// Query a record according to Wrapper
Map<String, Object> getMap(Wrapper<T> queryWrapper);
// Query a record according to Wrapper
<V> V getObj(Wrapper<T> queryWrapper, Function<? super Object, V> mapper);


(all questions are written in secondary headings, not in wrong format, but for convenience of query)

1. application.properties and application Differences between YML files

In the process of searching tutorials on the Internet, you can find that many tutorials are written in application YML, and never mentioned application Properties, which raises questions about whether they are the same thing and the product of different versions?

The answer is similar but inconsistent

Through brief contact, we can find that SpringBoot often defines attributes through external configuration.
The difference between the two lies in the different loading order and the clearer stratification of yml than properties

  • You can use the @ PropertySource annotation to load a custom Properties configuration file, but you cannot load a custom YAML file.
    YAML supports the configuration of lists, but Properties does not.

Original text from: www.hangge.com Com reprint, please keep the original link: https://www.hangge.com/blog/cache/detail_2459.html

2. What is H2 database?

H2 is a relational database written in Java. It can be embedded in Java applications or run as a separate database server. The predecessor of H2 database is HypersonicSQL. Its name means Hypersonic2, but its code is written from scratch without HypersonicSQL or HSQLDB code.
(source: Wikipedia)

3. About process' command 'C: / program files / Java / jdk-17.0.1/bin/java Exe '' finished with non zero exit value 1


  1. If possible, due to port conflict, you can change the port - > open application Properties, and then add server port=8082
  2. This happens when you have DB plugins in your project but you did not specify DB details in application.property file.
    There are database plug-ins, but you don't configure them accordingly, so you can check whether there is a problem with the corresponding configuration

  3. Or maybe it's a compiler problem?, intellij?, File - > invalidate cache... - > invalidate and restart, clear the cache and restart.
  4. build. There is a problem with the java version configured in gradle. Open cmd, enter java -version, check the java version, and then change build Set in gradle, as shown in the figure
  5. For some reason, you need to try to rebuild build Gradle, so you can consider clicking the refresh of gradle

4. What is a code generator?

  • Code generators are tools or resources that generate specific types of code or computer programming languages.

5. What is MapperScan?

After adding @ MapperScan("com.xxx") annotation, com The interface classes under XXX package will generate corresponding implementation classes after compilation, which solves the redundancy of Mapper's annotation one by one.
(according to online information, @ Mapper does not generate implementation classes during compilation, but through dynamic agents at runtime, source)
In addition, mappercan can annotate multiple packages at the same time

@MapperScan("com.xxx", "com.yyy")

6. About IntelliJ IDEA, prompt "Execution failed for task": xxapplication main()’. Solutions


Reference documents

Mybatis plus learning notes
Official documents
Introduction to Mybatis plus

Topics: C Algorithm