Mybatis plus makes it easy to get started

Posted by Jewbilee on Sat, 15 Jan 2022 05:19:24 +0100

1. Introduction to mybatis plus

Mybatis plus is an enhanced version of mybatis. Based on mybatis, only enhancements are made without changes. It is born to simplify development and improve efficiency.

2. What is mybatis plus, MP

No invasion: it is only enhanced without change, and its introduction will not affect the existing project, which is as smooth as silk
Low loss: the basic CURD will be injected automatically upon startup, with basically no loss of performance and direct object-oriented operation
Powerful crud operation: built in general Mapper and general Service, most CRUD operations of a single table can be realized only through a small number of configurations, and there is a powerful condition constructor to meet various use requirements
Support Lambda formal call: it is convenient to write various query conditions through Lambda expression, and there is no need to worry about wrong fields
Support automatic generation of primary key: support up to 4 primary key strategies (including distributed unique ID generator - Sequence), which can be configured freely to perfectly solve the primary key problem
Support ActiveRecord mode: support ActiveRecord formal calls. Entity classes only need to inherit Model classes to perform powerful CRUD operations
Support custom global general operations: support global general method injection (Write once, use anywhere)
Built in code generator: code or Maven plug-in can be used to quickly generate Mapper, Model, Service and Controller layer code, support template engine, and more custom configurations for you to use
The developer does not need to worry about the physical paging operation after the built-in paging plug-in is configured based on mylist. The specific paging operation is the same as that of the general paging plug-in
The paging plug-in supports multiple databases: MySQL, MariaDB, Oracle, DB2, H2, HSQL, SQLite, Postgre, SQLServer and other databases
Built in performance analysis plug-in: it can output Sql statements and their execution time. It is recommended to enable this function during development and testing to quickly find out slow queries
Built in global interception plug-in: it provides intelligent analysis and blocking of full table delete and update operations, and can also customize interception rules to prevent misoperation

3. Introduction case of mybatis plus

Core idea: using objects to operate database single table queries, almost no Sql is written

 

 

3.1 dependency of importing jar package

       

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.jt</groupId>
    <artifactId>springboot_demo3_MP</artifactId>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.2</version>
        <relativePath/>
    </parent>

    <properties>
        <java.version>1.8</java.version>
        <!--Skip test class packaging-->
        <skipTests>true</skipTests>
    </properties>

    <!--principle: Import on demand  -->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <!--springboot Startup item(implement)Inside the package SpringBoot
            The of the project has been completed"integration"(to configure) The user takes it and uses it
            web Import SpringMVC
            -->
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--Support hot deployment -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>

        <!--add to lombok rely on-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <!--Introducing database driver -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>

        <!--springBoot Database connection  -->

        <!--spring integration mybatis  temporary  -->
<!--        <dependency>-->
<!--            <groupId>org.mybatis.spring.boot</groupId>-->
<!--            <artifactId>mybatis-spring-boot-starter</artifactId>-->
<!--            <version>2.2.0</version>-->
<!--        </dependency>-->
        <!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.3.1</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

    </dependencies>

    <!--SpringBoot Project and Maven A plug-in for integration
        You can perform project packaging through plug-ins/test/Document generation and other operations
        matters needing attention: The plug-in cannot be omitted
        When the project is published: java -jar xxxx.jar  report errors:No master list information!!!!
    -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.5.2</version>
            </plugin>
        </plugins>
    </build>


</project>

Note: when integrating mybatis plus with springBoot, the jar package dependency of mybatis should be removed, otherwise it is easy to cause problems. It is thought that MP is an enhanced version of mybatis and contains all the functions of mybatis.

 3.2. Configure object relational mapping

@Data
@Accessors(chain = true)
@TableName("demo_user")
//The function of entity object is to pass parameters
//@Component / / there is no need to hand over the entity object to the Spring container for management
public class User implements Serializable {//Serialization: ensure data transmission integrity
    @TableId(type=IdType.AUTO)//Binding primary key auto increment
    private Integer id;
    //@TableField("name") / / if the attribute has the same name as the field (including hump rules), the annotation can be omitted
    private String name;
    private Integer age;
    private String sex;
}

3.3 inherit public API interface

//@Mapper//Mybatis creates a proxy object for the interface JDK dynamic proxy object
//Note: you must add a generic object when inheriting the interface, otherwise the mapping table will report an error and bind the User because the User and demo_ The User table is bound
public interface UserMapper extends BaseMapper<User> {
    //Query all demos_ User table data
    List<User> getAll();

}

   

/Note: you must add a generic object when inheriting the interface, otherwise the mapping table will report an error and bind the User because the User and demo_ The User table is bound

3.4 edit application YML file

     

server:
  port: 8090

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/jt?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
    username: root
    password: root
    #If the database password starts with the number 0, you must use the "" number
    #password: "01234"

#Spring boot integrates Mybatis configuration
mybatis-plus:
  type-aliases-package: com.jt.pojo
  mapper-locations: classpath:/mybatis/*.xml
  configuration:
    map-underscore-to-camel-case: true
  #  log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
#Mapper interface executes printing sql statements
logging:
  level:
    com.jt.mapper: debug

3.5 test tools

@SpringBootTest
public class TestSpringBootMP {
    @Autowired 
    private UserMapper userMapper;

    /**
     * New user
     */
    @Test
    public void testInsert(){
        User user = new User();
        user.setName("Kris").setId(100).setSex("male");
        userMapper.insert(user);
    }
    /**
     * MP:Operating a database with objects
     * Learning: code structure
     * Case 1: query data according to id=1
     */
    @Test
    public void getUserById(){
        User user = userMapper.selectById(1);
        System.out.println(user);
    }
    /**
     * Case 2: query data according to age = 18 sex = "female"
     */
    @Test
    public void getUserByAS(){
        User u = new User();
        u.setAge(18).setSex("female");
        //Build condition constructor to dynamically splice where conditions
        //Generate where conditions based on non null properties in the object. By default, and connections are used
        QueryWrapper queryWrapper = new QueryWrapper(u);
        List<User> list = userMapper.selectList(queryWrapper);
        System.out.println(list);
    }
    /**
     * Case 3: query data according to age > 18 sex = "female"
     * Special characters (xml file): > GT, < LT, = EQ
     *          >=ge , <=le ,!=ne
     *          xml Medium time & lt;
     */
    @Test
    public void getUserGT(){
        QueryWrapper<User> queryWrapper = new QueryWrapper();//We need a company If you want to add generics, you can connect points
        queryWrapper.gt("age", 18).eq("sex", "female");
        List<User> list = userMapper.selectList(queryWrapper);
        System.out.println(list);
        System.out.println("**********************");
        QueryWrapper<User> queryWrapper1 = new QueryWrapper();//We need a company If you want to add generics, you can connect points
        queryWrapper1.ge("age", 100).eq("sex", "female");
        List<User> list2 = userMapper.selectList(queryWrapper1);
        System.out.println(list2);
    }
    /**
     * Case 4: query the data containing "Jun" in name
     * sql: select * from demo_user where name like="%Jun%“
     */
    @Test
    public void testLike(){
        QueryWrapper<User> queryWrapper = new QueryWrapper();//We need a company If you want to add generics, you can connect points
        //queryWrapper.like("name", "Jun");
        // sql: select * from demo_user where name like = "% Jun"
        //queryWrapper. Likeleft ("name", "Jun");
        //Excluding Jun
        queryWrapper.notLike("name", "King");
        List<User> list = userMapper.selectList(queryWrapper);
        System.out.println(list);

    }
    /**
     * Case 5: query users with age > 18 and take photos in descending order of age. If they are the same age, they are sorted by sex
     * sql: SELECT * FROM demo_user  WHERE age>18 ORDER BY age DESC,sex
     */
    @Test
    public void testOrderBy(){
        QueryWrapper<User> queryWrapper = new QueryWrapper();//We need a company If you want to add generics, you can connect points
        queryWrapper.gt("age", 18)
                .orderByDesc("age","sex");
        List<User> list = userMapper.selectList(queryWrapper);
        System.out.println(list);

    }
    /**
     * Case 6: query data with id=1,3,5,6,7
     * sql: SELECT * FROM demo_user  WHERE id in(1,3,5,6,7)
     * Keyword: the efficiency of single label query in or is almost the same
     *          Multi table queries are recommended to use or for faster performance
     * Variable parameter type:
     *      1.The variable parameter type data structure is essentially an array.
     *      2.To define a variable parameter type, it must be in the last bit of the method parameter
     *      void addUser(Integer age,Integer ...ids) correct
     */
    @Test
    public void testIn(){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //MP special method calls. In the future, use object types as much as possible. Objects have methods
        //int[] ids = new int[]{1,3,5,6,7};
        //List idList = Arrays.asList(idList);
        Integer[] ids={1,3,5,6,7};
        queryWrapper.in("id",ids);
        List<User> userList = userMapper.selectList(queryWrapper);
        System.out.println(userList);

    }
    /**
     * Case 7: dynamically query the database according to name/sex
     */
    @Test
    public void testSelectNS(){
        String name = null;
        String sex = "female";
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        boolean nameFlag = StringUtils.hasLength(name);
        boolean sexFlag = StringUtils.hasLength(name);
        queryWrapper.eq(nameFlag, "name", name).eq(sexFlag, "sex", sex);
        List<User> userList = userMapper.selectList(queryWrapper);
        System.out.println(userList);
    }

    /**
     * 1. Delete data with ID=231
     */
    @Test
    public void testDeleteId(){
        userMapper.deleteById(231);
        System.out.println("Delete succeeded");

    }
    /**
     * 2. Delete data with id = 77232239
     */
    @Test
    public void testDeleteIds(){
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        List<Integer> userList = new ArrayList<>();
        userList.add(77);
        userList.add(232);
        userList.add(239);
        //updateWrapper.ge("id", userList);
        userMapper.deleteBatchIds(userList);
        System.out.println("Delete succeeded");
    }
    /**
     * 3. Delete data with name = "Wu Yifan", age=30
     *
     */
    @Test
    public void testDeletByName(){
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("name", "Kris").eq("age", 30);
        userMapper.delete(updateWrapper);
    }
    /**
     * 
     *  4. Modify the data of name = "Wu Yifan" to name = "wish you good luck" age=100
     */
    @Test
    public void testUpdateName(){
        UpdateWrapper<User> updateWrapper = new UpdateWrapper();
        User user = new User();
        user.setName("Good luck");
        user.setAge(100);
        updateWrapper.eq("name", "Kris");
        userMapper.update(user,updateWrapper);
        System.out.println("Modification succeeded!");
    }
/**
 * 
 *  5. Modify data with Id=11 name = "Yunying" sex = "male" age="16"
 */
    @Test
    public void testUpdateId(){
        UpdateWrapper<User> updateWrapper = new UpdateWrapper();
        User user = new User();
        user.setName("greisen");
        user.setSex("male");
        user.setAge(16);
        updateWrapper.eq("id", 11);
        userMapper.update(user,updateWrapper);
    }
}

4. Implementation principle of MP

1. The User performs the User object warehousing operation usermapper insert(User);
2. Since the generic object needs to be passed in the interface method, find the corresponding generic object according to the user configuration
3. Obtain the parent interface BaseMapper of Mapper interface according to the user's interface, and obtain the user information according to the generic object in BaseMapper Class type
4. According to user Class gets @ TableName("demo_user") dynamically to get the table name corresponding to the object Then bind the corresponding field through @ TableField("name") At this point, the object and table are mapped
5. Dynamically splice Sql statements according to the above mapping relationship
Example: usermapper How does insert (user object) convert Sql?
**insert into table name (field name...) values (attribute value...)
insert into demo_user(id,name,age,sex) values ("Wu xx", xx,xx,xx)
**
6.MP gives the dynamically generated Sql to Mybatis to perform the final data warehousing operation!!!
 

 5.MP usage

It has been described in detail in 3.5 and will not be introduced here

Topics: Mybatis