Download the original mind map, you can also leave a message to me, see it will reply

I am a student majoring in Internet of Things engineering. I write my blog not only to record my learning process, but also to help many budding students like myself. For, as retreat webs. Come on! Blog homepage :blog.csdn.net/qq_44895397

MyBatisPlus profile

A list,

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.

Second, the characteristics of

  • 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 — conditional 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
  • Supports multiple databases: supports MySQL, MariaDB, Oracle, DB2, H2, HSQL, SQLite, Postgre, SQLServer2005, SQLServer and other databases
  • 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 XML hot loading: Mapper’s CORRESPONDING XML supports hot loading and can even start without XML for simple CRUD operations
  • 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)
  • Support automatic keyword escape: support database keywords (order, key……) Automatic escape, but also custom keywords
  • 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
  • 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
  • Built-in Sql injection stripper: supports Sql injection stripper to effectively prevent Sql injection attacks

Introduction to MyBatisPlus

Use Spring Initializr to quickly initialize a Spring Boot project

Add dependencies

Mybatis -plus-boot-starter, MySQL

<! --mybatis-plus--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> The < version > 3.0.5 < / version > < / dependency > <! --mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>Copy the code

Three, configuration,

Add the MySQL database configuration to the application.properties configuration file

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus? serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=yky
Copy the code

Fourth, code writing

1. Mapper inherits BaseMapper interface

@Mapper
public interface StudentMapper extends BaseMapper<tStudent> {}Copy the code

2. Entity classes

Note the relationship between database table names and entity class names:

3. Start classes

5. Configure logs

Console output SQL statement:

Core profile configuration

# mybatis log mybatis - plus. The configuration. The log - impl = org. Apache. Ibatis. Logging. Stdout. StdOutImplCopy the code

Six, test,

@SpringBootTest
public class Mybatisplusdemo01ApplicationTests {

    @Autowired
    private StudentMapper studentMapper;

    @Test
    void contextLoads(a) {
        List<tStudent> students = studentMapper.selectList(null);
        for(tStudent s : students) { System.out.println(s); }}}Copy the code

CRUD interface of MyBatisPlus

A, the insert

1. Insert operation

Simply call the methods in the BaseMapper interface

// Insert operations
	@Test
	public  void  add(a){
		tStudent student = new tStudent();
		student.setName("A little tramp who likes to code.");
		student.setAge(19);
		studentMapper.insert(student);
	}
Copy the code

2. Primary key policy

(1) ID_WORKER

MyBatis-Plus default primary key policy is:ID_WORKERGlobally unique ID

(2) Self-increment strategy
  • To add a primary key automatically, configure the following primary key policies
    1. Primary key increment needs to be set at table creation time
    2. In the entity field@TableId(type = IdType.AUTO)
 @TableId(type = IdType.AUTO)
    private Integer id;
Copy the code
  • To affect the configuration of all entities, you can set the global primary key configuration
Mybatis -plus.global-config.db-config.id-type=autoCopy the code
  • Other primary key strategies:

Second, the update

1. Update by Id

@Test
public void updateStudent(a) {
    tStudent student = new tStudent();
    student.setId(1009);
    student.setName("Invincible in the East");
    studentMapper.updateById(student);
}
Copy the code

2. Automatic filling

(1) Add automatic fill field in database table

(2) Add annotations to entities
// Auto-fill
@TableField(fill = FieldFill.INSERT)
private Date create_time;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date update_time;
Copy the code

(3) Realize the meta-object processor interface

Note: Don’t forget to add the @Component annotation

@Component
public class MyMateObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("update_time".new Date(),metaObject);
        this.setFieldValByName("create_time".new Date(),metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("update_time".newDate(),metaObject); }}Copy the code
Matters needing attention
  • Fields must be declaredTableFieldAnnotation, attributefillSelect the corresponding policy, this statement tells Mybatis-Plus to reserve the injection of SQL fields
  • Filling processorMyMetaObjectHandlerDeclaration is required in Spring Boot@Componentor@Beaninjection
  • To distinguish FieldFill. XXX from the field name and field type, strictInsertFill or strictUpdateFill methods of the parent class must be used
  • There is no need to distinguish between the fillStrategy methods that can use the parent class

3. Optimistic Locking

Main solution: lost update, that is, to achieve thread-safe data update

1. Implementation of optimistic lock:
  1. When the record is fetched, the current version is retrieved
  2. When you update, take this version with you
  3. When performing an update, set version = newVersion where version = oldVersion
  4. If the version is incorrect, the update fails
2. Configuration Steps:
  1. The plug-in configuration
   /** * Optimistic lock plug-in */
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor(a) {
        return new OptimisticLockerInterceptor();
    }
Copy the code
  1. Add the @Version annotation to the version attribute in the entity class
/ / optimistic locking
    @TableField(fill = FieldFill.INSERT)
    @Version
    private Integer version;
Copy the code
3. Special notes
  1. Support for data types only int, Integer, long, long, the Date and Timestamp, LocalDateTime
  2. In the integer format, newVersion = oldVersion + 1
  3. NewVersion is written back to the entity
  4. Only updateById(ID) and Update (Entity, Wrapper) methods are supported
  5. The wrapper cannot be reused under the Update (Entity, wrapper) method!

Third, the select

1. Query records based on the ID

@Test
	void selecttStudentById(a) {
		tStudent students = studentMapper.selectById(1004);
		System.out.println(students);
	}
Copy the code

2. Batch query information using multiple ids

@Test
void selecttStudentById(a) {
	List<tStudent> tStudents = studentMapper.selectBatchIds(Arrays.asList(1001.1002.1003));
	System.out.println(tStudents );
}
Copy the code

3, simple conditional query

Map encapsulates query conditions

  • Note: Keys in the map correspond to column names in the database.
@Test
public void testSelectByMap(a){

    HashMap<String, Object> map = new HashMap<>();
    map.put("name"."A little tramp who likes to code.");
    map.put("age".19);
    List<User> users = userMapper.selectByMap(map);
    users.forEach(System.out::println);
}
Copy the code

4, paging query

MyBatis Plus has its own paging plug-in, as long as the simple configuration can achieve paging function

Add a paging plug-in to the configuration class
 @Bean
    public PaginationInterceptor paginationInterceptor(a) {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        // Set the request page to be larger than the maximum page operation, true to return to the home page, false to continue the request default false
        // paginationInterceptor.setOverflow(false);
        // Set the maximum number of pages per page, default 500, -1 is not limited
        // paginationInterceptor.setLimit(500);
        // Enable count join optimization for only part of the left join
        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
        return paginationInterceptor;
    }
Copy the code
Use of paging plug-ins
Create page object
// Create a Page object
	// Two parameters: the current page and the number of records displayed per page
	Page<tStudent> studentPage = new Page<>(1.3);
Copy the code
2, by calling the paging query method

@Test
public void pageHander(a){
	// Create a Page object
	// Two parameters: the current page and the number of records displayed per page
	Page<tStudent> studentPage = new Page<>(1.3);
	// Call the paging query method
	// Encapsulate all paging data into a page object
	studentMapper.selectPage(studentPage,null);
	studentPage.getCurrent();/ / the current page
	studentPage.getRecords();// A list of data per page
	studentPage.getSize();// Display the number of records per page
	studentPage.getTotal();// Total number of records
	studentPage.getPages();/ / the total number of pages
	System.out.println(studentPage.getPages());
	studentPage.hasNext();// Determine if there is a next page
	studentPage.hasPrevious();// Check if there is a previous page
}
Copy the code

Fourth, the delete

1. Delete records based on id

@Test
public void testDeleteById(a){
    int result = userMapper.deleteById(8L);
    System.out.println(result);
}
Copy the code

2. Delete them in batches

  @Test
    public void testDeleteBatchIds(a) {
        int result = userMapper.deleteBatchIds(Arrays.asList(8.9.10));
        System.out.println(result);
    }
Copy the code

3, simple condition query delete

@Test
public void testDeleteByMap(a) {

    HashMap<String, Object> map = new HashMap<>();
    map.put("name"."Helen");
    map.put("age".18);

    int result = userMapper.deleteByMap(map);
    System.out.println(result);
}
Copy the code

4. Logical deletion

  • Physical delete: Deletes the data from the database. The deleted data cannot be queried later
  • Logical deletion: False deletion. The state of the field representing whether the data is deleted or not is changed to deleted state. After that, the data record can still be seen in the database
(1) Add the deleted field to the database

(2) Add @tablelogic
 @TableLogic
    @TableField(fill = FieldFill.INSERT)
    private Integer deleted;
Copy the code
(3) Automatically fill in the deleted default value when new data is added

You do not need to set the default value when adding a deleted field in the database

this.setFieldValByName("deleted".0,metaObject);
Copy the code
(4) Application. Properties add configuration (optional)
#mybatis-plus.global-config.db-config.logic-delete-value=1 #mybatis-plus.global-config.db-config.logic-not-delete-value=0Copy the code

MyBatisPlus Conditional constructor

For more information, please refer to the official documentation: https://mp.baomidou.com/

Create a QueryWrapper object

QueryWrapper<tStudent> wrapper = new QueryWrapper<>();
Copy the code

1. Ge, GT, LE, LT, isNull, isNotNull

  • Ge: greater than or equal to >=
  • Gt: greater than >
  • Le: less than or equal to <=
  • Lt: Less than <
  • IsNull: indicates that the field IS NULL
  • IsNotNull: The field IS NOT NULL
public void text(a){
		QueryWrapper<tStudent> wrapper = new QueryWrapper<>();
		wrapper.ge("id".1004);
		wrapper.le("age".50);
		List<tStudent> tStudents = studentMapper.selectList(wrapper);
		System.out.println(tStudents);
	}
Copy the code

2. Eq, NE

  • Eq: equal to
  • Ne: No
eq("name"."Wang")--->name = 'Lao wang'
Copy the code

3. Between, notBetween

Contain size boundary

  • BETWEEN values 1 AND 2
between("age".18.30)--->age between 18 and 30
Copy the code

4, allEq

allEq(Map<R, V> params)
allEq(Map<R, V> params, boolean null2IsNull)
allEq(boolean condition, Map<R, V> params, boolean null2IsNull)
Copy the code
  • Case 1:AllEq ({id: 1, name: "wang", the age: null})—>Id = 1 and name = 'old' and age is null
  • Example 2:AllEq ({id:1, age:null}, false)—> Id = 1 and id = 1

5, the last

Ignore optimization rules and splice directly to the end of SQL

Matters needing attention:

  • You can only invoke the command once. If the command is invoked for multiple times, SQL injection risks. Exercise caution when invoking the command
  // Complex condition query
    @Test
    public void select(a){
        QueryWrapper<tStudent> wrapper = new QueryWrapper<>();

        wrapper.last("and name = ''");

        List<tStudent> tStudents = studentMapper.selectList(wrapper);

        System.out.println(tStudents);
    }
Copy the code