Original statement

This article was first published under the headline “Happyjava”. Happy nuggets address: juejin.cn/user/398428… , Happy’s personal blog: blog.happyjava.cn. Welcome to reprint, but keep this statement.

Mybatis plus introduction

Mybatis -Plus (MP for short) is a mybatis enhancement tool, on the basis of MyBatis only do enhancement do not change, to simplify the development and improve efficiency. It supports the following features:

  • No intrusion: only enhancements are made, no changes are made, and its introduction will not affect the existing project, as smooth as silk
  • Low loss: Basic CURD will be injected automatically upon startup, with basically no loss in performance and direct object-oriented operation
  • Powerful 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
  • Support Lambda form call: through Lambda expressions, it is convenient to write all kinds of query conditions, without worrying about field write errors
  • Support automatic generation of primary keys: support up to four primary key policies (including distributed unique ID generator – Sequence), can be freely configured, perfect solution to the primary key problem
  • Support for ActiveRecord mode: Support for ActiveRecord form calls, entity classes only need to inherit from Model classes to perform powerful CRUD operations
  • Support custom global universal operations: support Write once (use anywhere)
  • Built-in code generator: 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 to use
  • 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 equal to ordinary List query
  • The paging plug-in supports a variety of databases: MySQL, MariaDB, Oracle, DB2, H2, HSQL, SQLite, Postgre, SQLServer2005, SQLServer and many other databases
  • Built-in performance analysis plug-in: outputs 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: provides intelligent analysis and blocking of delete and UPDATE operations on all tables, and can customize interception rules to prevent misoperations

Mybatis Plus, the enhancement of Mybatis is not the least bit. The combination of the two can greatly improve the development efficiency. Currently, many Internet companies are using MyBatis Plus. Here, let’s get started with Mybatis Plus.

Quick start

Database tables (from official documentation) :

id name age email
1 Jone 18 [email protected]
2 Jack 20 [email protected]
3 Tom 28 [email protected]
4 Sandy 21 [email protected]
5 Billie 24 [email protected]

Construction sentences:

DROP TABLE IF EXISTS user;

CREATE TABLE user
(
	id BIGINT(20) NOT NULL COMMENT 'primary key ID'.name VARCHAR(30) NULL DEFAULT NULL COMMENT 'name',
	age INT(11) NULL DEFAULT NULL COMMENT 'age',
	email VARCHAR(50) NULL DEFAULT NULL COMMENT 'email',
	PRIMARY KEY (id));Copy the code

Data:

DELETE FROM user;

INSERT INTO user (id.name, age, email) VALUES
(1.'Jone'.18.'[email protected]'),
(2.'Jack'.20.'[email protected]'),
(3.'Tom'.28.'[email protected]'),
(4.'Sandy'.21.'[email protected]'),
(5.'Billie'.24.'[email protected]');
Copy the code

Introduction of depend on

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.1.1</version>
</dependency>
Copy the code

One is a mysql dependency and the other is a Mybatis – Plus dependency

Write the User.java entity class

@Data
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}
Copy the code

UserMapper interface

@Mapper
public interface UserMapper extends BaseMapper<User> {}Copy the code

Quick to use

After completing the above steps, you can start using MyBatis Plus.

@RunWith(SpringRunner.class)
@SpringBootTest
public class MybatisPlusApplicationTests {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void test1(a) {
        List<User> users = userMapper.selectList(null); users.forEach(e -> { System.out.println(e.toString()); }); }}Copy the code

Output result:

Write SQL through annotations

Select Insert, Update, and Delete from the list as follows:

@Mapper
public interface UserMapper extends BaseMapper<User> {

    @Select("select * from user where id = #{id}")
    User findUserById(int id);

}
Copy the code

Write SQL through XML configuration

To write SQL using XML, you need to configure the location of the XML:

mybatis-plus.mapper-locations=classpath:mappers/*.xml
Copy the code

The example XML configuration is as follows: usermapper.xml

<?xml version="1.0" encoding="UTF-8"? >
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="happy.mybatisplus.mapper.UserMapper">

    <select id="findUserByName" parameterType="string"
            resultType="happy.mybatisplus.entity.User">
        SELECT * FROM user WHERE name = #{name}
    </select>

</mapper>

Copy the code

These belong to the category of Mybatis, here will not do too much introduction.

Mybatis – plus commonly used

Here are some of the things that are commonly used in MyBatis – Plus:

1. Specify the name of the database table corresponding to the entity class

@TableName(value = "user")

Copy the code

Use in cases where the entity class does not correspond to the database, as in:

@Data
@TableName(value = "user")
public class UserEntity {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

Copy the code

2. Specify the name of the database field corresponding to the field

@TableField(value = "age")

Copy the code

Such as:

@Data
@TableName(value = "user")
public class UserEntity {
    private Long id;
    private String name;

    @TableField(value = "age")
    private Integer userAge;
    private String email;
}

Copy the code

3, insert data, get primary key

Call the insert method provided by Mybatis Plus. After execution, the primary key is set to the id attribute of the input parameter as follows:

4, paging

Configuring paging plug-ins:

@Bean
public PaginationInterceptor paginationInterceptor(a) {
    return new PaginationInterceptor();
}

Copy the code

Examples of paging:

conclusion

Mybatis – Plus has too many uses for springBoot to list them all. Interested friends, you can go directly to the official documents to view.