Why is Mybatis-plus so easy to use, but not used much?

1. What is Mybatis-plus?

MyBatis-Plus (MP for short) is an enhancement tool for mybatis. On the basis of mybatis, only enhancements are made and no changes are made. It is born to simplify development and improve efficiency.
insert image description here

2. Features

1. Moisturize things silently

Just make enhancements without changes, introduce it without affecting existing projects, silky smooth.

2. Efficiency first

With simple configuration, you can quickly perform single-table CRUD operations, saving a lot of time.

3. Rich functions

Code generation, automatic paging, logical deletion, autofill and other functions are all available.

3. Advantages

1. No intrusion

MyBatis-Plus is extended on the basis of MyBatis, only enhancements are made without changes. The introduction of MyBatis-Plus will not have any impact on the existing MyBatis framework, and MP supports all MyBatis native features.

2. Less dependence

Only rely on MyBatis and MyBatis-Spring

3. Small loss

The basic CRUD will be injected at startup, the performance is basically lossless, and the object-oriented operation is directly performed.

4. Prevent SQL Injection

Built-in SQL injection stripper to effectively prevent SQL injection attacks

5. General CRUD operations

With built-in general mapper and general service, most of the CRUD operations of a single table can be realized with only a small amount of configuration, and there are more powerful conditional constructors to meet various usage needs, a nightmare for CRUD programmers.

6. Multiple primary key strategies

Supports up to 4 primary key strategies (including distributed unique ID generator), which can be freely configured to perfectly solve the primary key problem.

  1. AUTO database ID auto increment
  2. INPUT User input ID
  3. ID_WORKER Globally unique ID, primary key of Long type
  4. ID_WORKER_STR string globally unique ID
  5. UUID Globally unique ID, the primary key of UUID type
  6. NONE This type is not set the primary key type

There are several ways to generate the primary key:

  1. database self-growth
  2. UUID
  3. Redis generates id

7. Support hot loading

The xml corresponding to mapper supports hot loading. For simple CRUD operations, it can even be started without xml.

Note: This function was removed in version 3.0.6, but the latest snapshot version has been added back and marked with an obsolete logo. It is expected to be completely removed in version 3.1.0

8. Support Active Record

Active Record (referred to as AR) is a domain model pattern, characterized in that a model class corresponds to a table in a relational database, and an instance of a model class corresponds to a row of records in the table.

MyBatis-Plus supports AR only by inheriting the Model class and implementing the primary key specification method.

9. Support code generation

Using code or Maven plug-in can quickly generate mapper, model, service, controller layer code, support template engine, the code generator class only needs to modify the table name, and enter the project package structure, it is easy and comfortable.

10. Support custom global general operations

Support global generic method injection

11. Support automatic escaping of keywords

Support automatic transfer of database keywords, and you can also customize keywords

12. Built-in paging plugin

Based on Mybatis physical paging, developers do not need to care about specific operations. After configuring the plug-in, writing paging is equivalent to writing a basic List query.

Pagination? A junior programmer's nightmare, now? so easy!

13. Built-in performance analysis plugin

It can output sql statement and execution time. It is recommended to enable it in the development and testing phase.

14. Built-in global interception plugin

Provide full table delete and update operations, intelligent analysis and block, to prevent misoperation.

Fourth, BaseMapper

In the use of MyBatis-Plus, we often use the BaseMapper interface. I wrote this blog because of BaseMapper. It is really a rookie.

BaseMapper is an implementation mechanism using MyBatis interface programming. It provides a series of basic methods for adding, deleting, modifying and checking by default, and developers do not need to write SQL for these basic operations to process operations (The mechanism provided by Mybatis requires developers to perform operations in mapper. xml provides the sql statement), so we can guess that Mybatis-Plus has completed the generation of the SQL statement of the method provided by the BaseMapper interface.

BaseMapper class:

package com.baomidou.mybatisplus.core.mapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;
 
public interface BaseMapper<T> {
    
    
    int insert(T var1);
 
    int deleteById(Serializable var1);
 
    int deleteByMap(@Param("cm") Map<String, Object> var1);
 
    int delete(@Param("ew") Wrapper<T> var1);
 
    int deleteBatchIds(@Param("coll") Collection<? extends Serializable> var1);
 
    int updateById(@Param("et") T var1);
 
    int update(@Param("et") T var1, @Param("ew") Wrapper<T> var2);
 
    T selectById(Serializable var1);
 
    List<T> selectBatchIds(@Param("coll") Collection<? extends Serializable> var1);
 
    List<T> selectByMap(@Param("cm") Map<String, Object> var1);
 
    T selectOne(@Param("ew") Wrapper<T> var1);
 
    Integer selectCount(@Param("ew") Wrapper<T> var1);
 
    List<T> selectList(@Param("ew") Wrapper<T> var1);
 
    List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> var1);
 
    List<Object> selectObjs(@Param("ew") Wrapper<T> var1);
 
    IPage<T> selectPage(IPage<T> var1, @Param("ew") Wrapper<T> var2);
 
    IPage<Map<String, Object>> selectMapsPage(IPage<T> var1, @Param("ew") Wrapper<T> var2);
}

5. Use Mybatis-plus to realize addition, deletion, modification and inspection

1. Controller layer

@Controller
@RequestMapping("/user")
public class UserController {
    
    

    @Autowired
    private UserService userService;
    
	public void query(){
    
    
        Map<String, String> map = new HashMap<String, String>();
        map.put("userName","哪吒");
        List<User> userList = userService.query().allEq(paramMap).list();
    }

    @PostMapping("/save")
    public void save(User user){
    
    
        userService.save(user);
    }

    @PostMapping("/update")
    public void update(User user){
    
    
        userService.updateById(user);
    }

    @PostMapping("/delete")
    public void delete(String userId){
    
    
        userService.removeById(userId);
    }
}

Knowledge Expansion >>
Condition Constructor
Condition Constructor is to assemble various conditions to complete the query of different conditions, such as eq (equal to), gt (greater than), orderBy (sort), having, groupBy, between, etc., Conditional assembly is performed by translating these operators in SQL into code.
Personally, the conditional constructor is a bit like hibernate. It maps database operations to object operations, which is more in line with the programmer's thinking, but there are also certain drawbacks.
For example, if the project reports an error, it is difficult to locate the specific sql. There is no direct writing of sql. Mybatis-plus is rarely considered in the actual development process.

2. Service layer

public interface UserService extends IService<User> {
    
    

}
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {
    
    
	
}

3. Dao layer

@Mapper
public interface UserDao extends BaseMapper<User> {
    
    

}

4. Paging

(1) Paging configuration class

@Configuration
public class MybatisPlusConfig {
    
    

    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
    
    
        return new PaginationInterceptor();
    }
}

(2)controller

@Controller
@RequestMapping("/user")
public class UserController {
    
    

    @Autowired
    private UserService userService;
    
    // 分页
	@RequestMapping(value = "/findAll",method = RequestMethod.POST)
    public Object findAll(HttpServletRequest request){
    
    
        //获取前台发送过来的数据
        Integer pageNo = Integer.valueOf(request.getParameter("pageNo"));
        Integer pageSize = Integer.valueOf(request.getParameter("pageSize"));
        IPage<User> page = new Page<>(pageNo, pageSize);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        User user= new User();
        user.setId(1);
        wrapper.setEntity(user);
        return userService.page(page,wrapper);
    }
}

This code, absolutely, really concise. It's too late to meet you, I have written useless code for so many years! ! !

5. I remember SpringMVC's three-tier architecture, it's not like this.

(1) Presentation layer:

Receive the parameters passed from the front desk, and then pass these parameters to the business layer for processing. The business layer then returns the processed data to the presentation layer, and the presentation layer returns the data to the page and makes a page jump.

(2) Business layer:

Receive the parameters from the presentation layer and process the business logic. In the process of business processing, data may be manipulated from the database, so the business layer will not operate the database by itself, but will hand over the task of operating the database to the persistent layer processing.

(3) Data persistence layer:

Receive the parameters passed by the business layer, perform interactive processing of the database, and return the results of operating the database to the business layer.

That's right!

But what the hell is Mybatis-plus?

The presentation layer controller, the business layer service, and the data persistence layer dao do not have a single method, and they are all covered directly in the controller layer.

Many people say that this is not very good, but here is the problem

  1. For example, if the project reports an error, it is difficult to locate the specific sql, and there is no direct way to write the sql.
  2. Poor code readability
  3. Not good for sql optimization

Although Mybatis-plus can make your code more concise and has the 14 advantages mentioned above, it also reduces code reuse and hierarchy clarity, and greatly increases code modification and maintenance costs.

The service layer code and the database access layer code are confused together, making it difficult for programmers to focus on a particular detail. Common SQL operations Mybatis-plus can construct SQL execution conditions through Wrapper. Programmers cannot see SQL statements, and reading and checking SQL logic is more energy-consuming. Mybatis-plus is only based on later maintenance costs. The trade-off is the advantage of seemingly neatness in development.

6. Summary

In a word, do not use Mybatis-plus in actual development except for single-table brainless operation.

Nezha Essence Article Summary

Summary of 100,000 words and 208 Java classic interview questions (with answers)

Guess you like

Origin blog.csdn.net/guorui_java/article/details/126375530