Mybatis plus from entry to mastery (all)

Keywords: Java Mybatis


When learning mybatis plus
Need to master some knowledge points

  1. Zero foundation of java from entry to mastery (all)
  2. 200000 word summary of javaSE from entry to mastery (I)
  3. 200000 word summary of javaSE from entry to mastery (2)
  4. 200000 word summary of javaSE from entry to mastery (3)

as well as

  1. Spring framework from introduction to learning (full)
  2. Spring MVC from entry to mastery (full)
  3. springboot from entry to mastery (full)
  4. Mybatis from introduction to mastery (all)
  5. Maven detailed configuration (full)
  6. Maven actual combat from introduction to mastery (all)
  7. lambda expressions in java

The summary of learning knowledge points in this article is mainly through this link
MyBatis plus combat video tutorial - take you to quickly master MyBatis plus

  • Mybatis directly executes sql statements, which are written in xml files. Using mybatis requires
    It is cumbersome to multiple xml configuration files to some extent. Generally, the operation of database involves
  • Mybatis plus is an enhancement on mybatis, which reduces the configuration of xml and hardly needs to write xml
    The CURD of a single table can be achieved, which greatly provides the efficiency of development. It also provides various query functions and paging behavior

1. Introduction project

The specific steps are

  • Create project and add dependency
  • Create entity classes, define attributes, and define primary key types
  • Create dao interface and inherit BaseMapper entity class
  • Add package for scanning dao interface in startup class

Inject dao interface into test class or service to implement dynamic proxy and create dao implementation class object
Call the method in BaseMapper to complete the database addition operation

1.1 database

Create the database file first

Create a table

Remember to set a self increment function for the primary key of the database
Otherwise, there will be such a bug
Field 'id' doesn't have a default value appears; Nested exception is the solution of java.sql.sqlexception

In the code connection database
The code needs to set the connection port account, password and database dependent files

Create a project first

Create a configuration file to connect to the database in your code

    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://
    username: root
    password: 123456

The dependency file of mybatis plus needs to be introduced additionally

<!-- mybatis-plus -->

And the dependent files of the database


Here is the relevant part of the database

1.2 project construction

The next step is to build an entity class
The name of the entity class should be the same as the database name

        type = IdType.AUTO
private Integer id;
private String name;  // null
private String email;
//Entity class attribute. It is recommended to use wrapper type to judge whether it is null
private Integer age; // 0

You can automatically generate entity class get, set and other methods by using @ data annotation
Detailed analysis of @ Data annotation in spring
It can also be set manually

You can see that there are annotations on the entity class
It roughly means

  • value: the name of the primary key field. If it is an id, it can be left blank
  • Type: Specifies the type of the primary key and how the value of the primary key is generated. idType.AUTO indicates automatic growth

mapper class, that is, DAO interface
To implement BaseMapper, specify the entity class

public interface UserMapper extends BaseMapper<User> {

The specific BaseMapper class definition source code is as follows

It mainly defines 17 operation methods (CRUD) for the objects in this framework

Add an annotation scan in the startup class to scan this class
@MapperScan: scanner that specifies the package where the Mapper class is located

@MapperScan(value = "")
public class PlusApplication {

    public static void main(String[] args) {, args);

Test file

The annotation @ SuppressWarnings is mainly used to suppress warning values
See my previous articles for specific information
Detailed analysis of @ SuppressWarnings annotation in Spring

For @ RunWith(SpringRunner.class), the Test class needs to use the injected class, such as the class injected by @ Autowired, before it can be instantiated into the spring container

public class UserTest {

    //Define StudentMapper
    private UserMapper userDao;

    public void testInsertStudent() {
        User user = new User();
        int rows = userDao.insert(user);
        System.out.println("inserStudent rows:" + rows);

2. Configure log

Print log in console
Output database information

Mainly in yml configuration
The specific information is

    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

3. Basic usage of curd

The complete code is not written, only the core code

The specific methods are derived from basemapper < T >

3.1 insertion operation

//After adding data, get the primary key value
public void testInsertGetId(){
    User user  = new User();
    user.setName("Li Si");

    int rows  = userDao.insert(user);
    System.out.println("insert user rows:"+rows);

    //Get the primary key id, which is the id of the data just added to the database
    int id = user.getId();//get method corresponding to the primary key field
    System.out.println("Primary key id:"+id);


3.2 update operation

  • If the number of attributes is used, the updated number will be displayed
  • It is best to use classes of wrapper type

When defining entity classes, it is best to use wrapper types as follows:

  • Defines the basic type of an entity class. If it is not updated, it will be given 0 by default, that is, it will be updated
  • Define the entity class wrapper type. If it is not updated, it is null by default, but if it is updated, it is an updated non null type.
public void testUpdateUser(){
    User user = new User();
    user.setName("Modified data");
    //Perform an update based on the primary key value
    /*UPDATE user SET name=?, email=?, age=? WHERE id=?
     *All non null attribute values are updated, and the condition where id = primary key value
    int rows = userDao.updateById(user);
    System.out.println("update rows:"+rows);

3.3 delete

  • Delete a piece of data by primary key
    The method is deleteById()
public void testDeleteById(){

    //DELETE FROM user WHERE id=?
    int rows  = userDao.deleteById(3);
  • Delete the data by conditions, which are encapsulated in the Map object
    The method is deleteByMap(map object);
public void testDeleteByMap(){
    //Create a Map object and save the condition value
    Map<String,Object> map  = new HashMap<>();
    //put("field name of table", condition value), which can encapsulate multiple conditions
    //Call delete method
    //DELETE FROM user WHERE name = ? AND age = ?
    int rows = userDao.deleteByMap(map);
    System.out.println("deleteByMap rows:"+rows);

  • Use multiple primary key values to delete data
    Use the list by deleteBatchIds()
public void deleteByBatchId(){
    List<Integer> ids  = new ArrayList<>();

    //Delete operation
    //DELETE FROM user WHERE id IN ( ? , ? , ? , ? , ? )
    int i = userDao.deleteBatchIds(ids);


lambda expressions can also be used for deletion
Replace the code listed above with

 //Create a List collection using lambda
List<Integer> ids = Stream.of(1, 2, 3, 4, 5).collect(Collectors.toList());

3.4 query operation

  • Query according to the primary key value. The method is selectById
public void testSelectById(){
     * Generated sql: SELECT id,name,email,age FROM user WHERE id =?
     * If no data is found according to the primary key, the returned value is null
    User user = userDao.selectById(6);

    //Before using an object, you need to determine whether the object is null
    if(user != null){
        //Call of business method

  • Implement batch query, query according to multiple primary key values, and obtain the List
    The method is selectBatchIds
public void testSelectBatchId(){
    List<Integer> ids = new ArrayList<>();

    //Query data
    //SELECT id,name,email,age FROM user WHERE id IN ( ? , ? , ? )
    List<User> users = userDao.selectBatchIds(ids);
    for (User u:users){
        System.out.println("Query user:"+u);

You can also use lambda expressions for queries

List<Integer> ids = Stream.of(6, 9, 10, 15).collect(Collectors.toList());
  • Multi criteria query using Map
    The method is selectByMap()
public void testSelectMap(){
    //Create a Map to encapsulate query criteria
    Map<String,Object> map = new HashMap<>();
    //key refers to the field name, value refers to the field value, and multiple keys refer to and connection

    //Query according to Map
    //SELECT id,name,email,age FROM user WHERE name = ? AND age = ?
    List<User> users = userDao.selectByMap(map);
    users.forEach(user -> {


4. ActiveRecord

  • ActiveRecord is responsible for persisting itself and encapsulating access to the database in ActiveRecord
    Q. implement CRUD by the object itself to realize elegant database operation
  • ActiveRecord also encapsulates some of the business logic. It can be used as a business object

The following chapters also talk about the usage of adding, modifying and checking (I won't list the subheadings)

The main difference is

  • The former needs to inject mapper and use the classes inherited from mapper (implement curd)
  • Now it is not necessary to inject mapper, but inherit extends Model<Dept> through entity class, and then call model class to implement curd.
//Using automatic injection, inject Mapper objects (Dao)
private UserMapper userDao;

View the source code in the model class

Same as the previous steps

  • Create a table in the database
  • Create an entity class with the same attribute in the code

When using AR, the entity class needs to inherit the Model in MP, which provides operations on the CRUD of the database

mapper files should also be written
Because DeptMapper does not need to be used, MP needs to use DeptMapper to obtain the table information of the database.
If deptmapper is not defined, MP will report an error and cannot find the definition information of the table

public interface DeptMapper extends BaseMapper<Dept> {

Remember to add this annotation to the test class

For @ RunWith(SpringRunner.class), the Test class needs to use the injected class, such as the class injected by @ Autowired, before it can be instantiated into the spring container

The specific test classes are as follows

4.1 insertion operation

The insert method in the model is called

public void testARInsert(){
    //Defines the entity of dept

    Dept dept  = new Dept();
    dept.setName("Administration Department");
    //Call the entity object's own method to complete the addition of the object itself to the database
    boolean flag = dept.insert();
    System.out.println("ar insert result:"+flag);

4.2 update operation

public void testARUpdate(){
    //Define entity Dept
    Dept dept  = new Dept();
   // dept.setId(2);
    dept.setName("Changed to marketing department");
    //Update record based on primary key id
    // UPDATE dept SET name=?, mobile=?, manager=? WHERE id=?  // id = 1
    boolean result = dept.updateById();//Use the value of dept entity primary key as where id = 1
    System.out.println("ar updateById result:"+result);

Update as many attributes as you write (the definition of prerequisite attributes are all wrapper types)

public void testARUpdate2(){
    //Define entity Dept
    Dept dept  = new Dept();
   // dept.setId(1);
    //Name and manager are not modified

    //Update record based on primary key id
    // UPDATE dept SET name=?, mobile=?, manager=? WHERE id=?  // id = 1
    // Null property values are not updated, and there are no null fields in update
    //UPDATE dept SET mobile=? WHERE id=?
    boolean result = dept.updateById();//Use the value of dept entity primary key as where id = 1
    System.out.println("ar updateById result:"+result);

4.3 delete

  • The deleteById() delete operation returns true even if it does not delete data from the database
public void testARDeleteById(){
    Dept dept  = new Dept();
    //DELETE FROM dept WHERE id=?
    boolean result = dept.deleteById(1);
    System.out.println("ar deleteById result:"+result);

4.4 query operation

Method selectByID

  • Data can be found and objects can be returned according to the primary key of the entity
  • Data cannot be found according to the primary key of the entity. It is null and no error is reported
  • null is also returned if there is no record or no data
public void testARSelectById(){
    Dept dept = new Dept();
    //Set the value of the primary key
  // dept.setId(1);
    //Call query method
   //SELECT id,name,mobile,manager FROM dept WHERE id=?
   Dept dept1 = dept.selectById();
   System.out.println("ar selectById result:"+dept1);

public void testARSelectById2(){
    Dept dept = new Dept();
    Dept dept1 = dept.selectById(3);


Posted by evan12 on Thu, 18 Nov 2021 02:11:59 -0800