“This is the first day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021”

What is it?

Mybatis – Plus is myBatis enhancement kit – do enhancements without changes, simplify CRUD operation.

  • Non-intrusive: Mybatis Plus is an extension of Mybatis with only enhancements and no changes, the introduction of Mybatis Plus will not affect your existing Mybatis architecture, and MP supports all Mybatis native features
  • Less dependencies: only rely on Mybatis and Mybatis-Spring
  • Low loss: Basic CURD will be injected automatically upon startup, with basically no loss in performance and direct object-oriented operation
  • Universal CRUD operations: built-in universal Mapper, universal Service, only through a small amount of configuration can achieve a single table most CRUD operations, more powerful condition constructor, to meet all types of use requirements
  • Multiple primary key policies: support up to 4 primary key policies (including distributed unique ID generator), can be configured freely, perfect solution to the primary key problem
  • ActiveRecord support: ActiveRecord calls are supported, and entity classes only need to inherit from Model classes to implement basic CRUD operations
  • Support code generation: using code or Maven plug-in can quickly generate Mapper, Model, Service, Controller layer code, support template engine, more than a lot of custom configuration you use (P.S. More powerful than Mybatis official Generator!
  • Support custom global universal operations: support Write once (use anywhere)

– Built-in paging plug-in: Based on Mybatis physical paging, developers do not need to care about specific operations, after configuring the plug-in, write paging is the same as writing basic List query

  • Built-in performance analysis plug-in: Outputs Sql statements and their execution time. You are advised to enable this function during test development to effectively solve slow queries
  • Built-in global interception plug-in: provides intelligent analysis and blocking of delete and UPDATE operations on all tables to prevent misoperations

Second,Official Reference Documents baomidou.com/guide/

Powerful wrapper

Mybatis -plus wapper inheritance diagram

Introduction to Wraper:

  1. Wrapper: Conditional constructs an abstract class, the top parent class, which provides four methods to display the source code west
  2. AbstractWrapper: A WHERE condition used to encapsulate query conditions and generate SQL
  3. AbstractLambdaWrapper: Lambda syntax uniformly handles parsing Lambda to fetch column using Wrapper.
  4. LambdaQueryWrapper: The query Wrapper used for Lambda syntax
  5. LambdaUpdateWrapper: Lambda updates the Wrapper
  6. QueryWrapper: Entity object encapsulates action classes, not in lambda syntax
  7. UpdateWrapper: Update conditional wrapper for Entity object Update operations

Such as:

QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("name"."zhangsan");
queryWrapper.ge("age"."18"); .// You can continue to use the functions shown in the following figure to concatenate SQL.
Copy the code

Function description:

Any subclass of AbstractWrapper can use the following function.

Four, code actual combat

Source code address:Github.com/Dr-Water/my…

Sample source code directory structure:

  1. A new SpringBoot project introduces the following dependencies
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <! -- Mybatis plus core dependencies -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.1 track</version>
        </dependency>
    </dependencies>
Copy the code
  1. Database configuration file:
Spring. Application. Name =mp Spring. Datasource. Driver-class-name = com.mysql.cj.jdbc.driver # datasource name spring. Datasource Spring. The datasource. Url = JDBC: mysql: / / localhost: 3306 / mybatis - plus? ServerTimezone = # UTC&characterEncoding = utf-8 database user name & password: Spring. The datasource. The username = root spring. The datasource. The password = 123456 # print mybatis - plus SQL logs Mybatis - plus. The configuration. The log - impl = org. Apache. Ibatis. Logging. Stdout. # StdOutImpl mybatis mapper defined position Mybatis -plus.mapper-locations= classpath*:/mappers/*.xml Multiple packages are separated by commas or semicolons mybatis- Plus.typeAliasespackage =com.ratel.mp.entityCopy the code
  1. entity
package com.ratel.mp.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Builder;
import lombok.Data;


/** * @ Service description: *@package_name: com. Ratel. Mp. The entity *@project_name: mybatis - plus - demo *@author: [email protected] *@create_time: 2020-12-13 10:14
 * @copyright(c) Ratelfu All Rights Reserved */
@Data
@Builder
public class User {
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;
    private String name;
    private Integer age;
    private String email;
}

Copy the code
  1. dao
package com.ratel.mp.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ratel.mp.entity.User;
import org.apache.ibatis.annotations.Param;

/** * @ Service description: *@package_name: com. Ratel. Mp *@project_name: mybatis - plus - demo *@author: [email protected] *@create_time: 2020-12-02 20:45
 * @copyright(c) Ratelfu All Rights Reserved */
public interface UserDao extends BaseMapper<User> {
    /** * custom getById *@param id
     * @return* /
    User myGetById(@Param("id") Integer id);
}

Copy the code
  1. mapper

      
<! DOCTYPEmapper PUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.ratel.mp.dao.UserDao">
<! SQL > alter table SQL > alter table SQL

    <select id="myGetById" resultType="com.ratel.mp.entity.User">
        select * from user where id=#{id}
    </select>
</mapper>
Copy the code
  1. service
package com.ratel.mp.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.ratel.mp.entity.User;

/** * @ Service description: *@package_name: com. Ratel. Mp. Service *@project_name: mybatis - plus - demo *@author: [email protected] *@create_time: 2020-12-13 10:34
 * @copyright(c) Ratelfu All Rights Reserved */
public interface UserService extends IService<User> {
    User myGetById(Integer id);
}

Copy the code
  1. serviceImpl
package com.ratel.mp.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ratel.mp.dao.UserDao;
import com.ratel.mp.entity.User;
import com.ratel.mp.service.UserService;
import org.springframework.stereotype.Service;

/** * @ Service description: *@package_name: com. Ratel. Mp. Service *@project_name: mybatis - plus - demo *@author: [email protected] *@create_time: 2020-12-13 10:36
 * @copyright(c) Ratelfu All Rights Reserved */
@Service
public class UserServiceImpl extends ServiceImpl<UserDao.User> implements UserService {
    @Override
    public User myGetById(Integer id) {
    	//baseMapper is already defined and injected for ServiceImpl. There is no need to define and inject again
        returnbaseMapper.myGetById(id); }}Copy the code
  1. Simple crud

package com.ratel.mp;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ratel.mp.entity.User;
import com.ratel.mp.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
class MpApplicationTests {

    @Autowired
    private UserService userService;

    @Test
    void queryTest(a){
        //
        List<User> userList = userService.list(Wrappers.<User>query().eq("id".1));
        System.out.println(userList);

        / / lambda method
        List<User> list = userService.list(Wrappers.<User>lambdaQuery().eq(User::getId,1));
        list.forEach(System.out::println);

        Eq (eg: id=1 and name = 'zs'...) //new LambdaQueryWrapper<>(entity)
        // Easy to use for daily development, such as the front end will be based on id/name/age/email any one or more of the four types of query, list, manual one. Eq is too troublesome, can use this method
        List<User> list2 = userService.list(Wrappers.<User>lambdaQuery(User.builder().id(1).build()));
        list.forEach(System.out::println);
    }
    @Test
    void saveTest(a){
        // Since the primary key is incremented, there is no need to set the id value here
        boolean isSuccess = userService.save(User.builder().name("zhangsan").age(18).email("[email protected]").build());
        System.out.println(isSuccess);
    }
    @Test
    void updateTest(a){
        User user = User.builder().name("zhangsan2").age(20).email("[email protected]").build();
        boolean isSuccess = userService.update(user, Wrappers.<User>update().eq("id".13));
        System.out.println(isSuccess);

        // Used to form the WHERE part of the UPDATE statement
        User condition = User.builder().id(13).build();
        UpdateWrapper<User> updateWrapper = Wrappers.<User>update(condition)
                .setSql("name=" + "'zhangsan3'," + "age=" + 18); // Set statement (name=zs, age=18...)
        boolean isSuccess2 = userService.update(updateWrapper);
        System.out.println(isSuccess2);
    }

    @Test
    void deleteTest(a){
        boolean isSuccess = userService.removeById(14);
        System.out.println(isSuccess);
        // Delete a nonexistent data return false
        boolean isSuccess2 = userService.removeById(-1);
        System.out.println(isSuccess2);
    }
    // Test custom code
     @Test
    void myGetByIdTest(a){
        User user = userService.myGetById(1); System.out.println(user); }}Copy the code

5. Reference Articles

  1. How is Mybatis Plus BaseMapper method injected
  2. Mybatis Plus powerful conditional constructor QueryWrapper conditional constructor base method explanation