MyBatis Plus explain in detail that learning is making money


Introduction: Mybatis plus is an enhanced tool of Mybatis. After using Mybatis plus, we can not only use the unique functions of Mybatis plus, but also use the native functions of Mybatis normally. It provides some interesting plug-ins to simplify development and improve development efficiency, such as SQL performance monitoring, optimistic lock, execution analysis, etc. Necessary artifact for senior fishing engineer!!!

Preliminary preparation:
Mybatis plus official website document connection address https://mp.baomidou.com

Mysql database:

DROP TABLE IF EXISTS `person`;
CREATE TABLE `person` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `name` varchar(255) DEFAULT '' COMMENT 'name',
  `sex` varchar(255) DEFAULT NULL COMMENT 'Gender',
  `hobby` varchar(255) DEFAULT NULL COMMENT 'hobby',
  `version` int(11) NOT NULL DEFAULT '0' COMMENT 'edition',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

Current version of mybatis plus:

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus</artifactId>
    <version>3.4.2</version>
</dependency>

Mybatis plus configuration of Spring Boot project:
1, Configuring MapperScan annotations

@SpringBootApplication
@ComponentScan(basePackages = {"com.zhu"})
//TODO scans Dao interface or Mapper here
@MapperScan("com.zhu.**.dao")
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

application.properties:

server.port=8080
logging.level.com.geely.gbop=debug
#JDBC Connection URL
spring.datasource.url = jdbc:mysql://127.0.0.1:3306/demo?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=GMT%2B8
#JDBC user name
spring.datasource.username=root
#JDBC password
spring.datasource.password=root
# Data connection pool
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# Database driven
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.mapper-locations=classpath*:mappers/*.xml
mybatis.config-location=classpath:mybatis/mybatis-config.xml

#Mybatis-plus mybatis scanning
mybatis-plus:
mybatis-plus.mapper-locations=classpath:/mappers/**/*.xml
# Log output
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

Dao entity class object:

@Data
@Builder
@TableName(value = "person")
public class PersonDO {

    @TableId(value = "id")
    private int id;

    @TableField(value = "name")
    private String name;

    @TableField(value = "sex")
    private String sex;

    @TableField(value = "hobby")
    private String hobby;

    @TableField(value = "version")
    @Version
    private int version;
}

For some annotations used in Dao objects, you can directly click the link to enter the official website document for details: Mybatis plus annotation details learning

PS: carefully, you will find a @ Version annotation. In fact, this annotation is used to set the database Version field to + 1 by default every time you do RUD. However, when using this annotation, you need to add an optimistic lock plug-in:

 // Scan our mapper folder
 @MapperScan("com.kuang.mapper")
 @EnableTransactionManagement
 @Configuration // Configuration class 
   public class MyBatisPlusConfig { 
   // Register optimistic lock plug-in 
   @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
    return new OptimisticLockerInterceptor(); 
  }
 }

Next, let's simply learn the Service CRUD interface - >

@Repository // Represents the persistence layer
public interface PersonMapper extends BaseMapper<PersonDO> {
    // It inherits BaseMapper, and all methods use their own parent class
    //  We can also write our own extension methods! Support XMl to write complex SQL statements
}



Look carefully. In fact, we haven't encapsulated the methods and statements. How can mybatis plus help us execute or encapsulate them!

Originally, when we wrote Mapper layer interface, we realized BaseMapper in mybatis plus, which has helped us write common single table query statements. We only need to realize the interface through the interface and call the methods written by others to execute SQL statements to achieve our purpose, Let me summarize the common APIs, so I won't show you the code one by one. If you are interested, you can try one by one!!!

PS: mybatis plus is developed by Chinese people, so it is familiar with our writing habits in name naming!

insert() // newly added
update() // You can pass in the condition constructor and modify it according to the condition
updateById() // Modify according to id
selectList() // Query collection, you can pass in the condition constructor
selectById() // Query a single record by id
selectPage() // Paging query, you can pass in the condition constructor
delete() // The condition constructor can be passed in and deleted according to the condition
deleteById() // Delete a single record by id
deleteMap() // Delete according to map collection
deleteBatchIds() // Batch delete

After learning the simple CRUD, I will learn the query condition builder (Wapper) of mybatis plus

Before learning Wapper, let's take a look at its class diagram structure:

explain:
QueryWrapper(LambdaQueryWrapper) and UpdateWrapper(LambdaUpdateWrapper) Parent class of
 Used to generate sql of where condition, entity Properties are also used to generate sql of where condition
 be careful: entity Generated where Conditions and usage api Generated where The condition has no associated behavior

Class diagram key class description:

Wrapper :  Conditional construction abstract class, topmost parent class
AbstractWrapper :  Used for query condition encapsulation and generation sql of where condition
QueryWrapper :  Entity Object encapsulates the operation class instead of using lambda grammar
UpdateWrapper :  Update Conditional encapsulation for Entity Object update operation
AbstractLambdaWrapper :  Lambda Syntax usage Wrapper Unified processing and analysis lambda obtain column. 
LambdaQueryWrapper : You can also understand by looking at the name, which is used for Lambda Query used by syntax Wrapper
LambdaUpdateWrapper :  Lambda Update encapsulation Wrapper

Pay special attention to the official document warning:


See here, I believe you have understood what is going on with the conditional constructor, ha!
In fact, the query conditions behind Where are spliced in the SQL statement we wrote. For more Api methods, please move to the official document for learning and testing: Detailed explanation of Wapper condition constructor!!!

After learning this, I believe you have a certain understanding of MyBatis plus. It is suggested that you can watch the learning video of broken station little crazy God for learning. It is really convenient for a simple small background system to use this. If the business still needs to write complex SQL statements with MyBatis XML, MyBatis plus is also supported, and you can make rational use of it according to the situation! There is also about general Mapper on the blog. If you are interested, you can also Look and Look for more support!!!

Learning link: https://www.bilibili.com/video/BV17E411N7KN

Keywords: Java

Added by vanessa123 on Wed, 02 Mar 2022 03:03:46 +0200