Mybatis – plus and mybatis
#####mybatis
Mybatis is an excellent persistence layer framework that supports customized SQL, stored procedures, and advanced mapping. MyBatis avoids almost all of the JDBC code and manual setting of parameters and fetching result sets. MyBatis can configure and map native information using simple XML or annotations to map interfaces and Java’s POJOs(Plain Old Java Objects) to records in the database.
However, mybatis has a headache for me is that THE SQL workload is very large, especially when there are many fields. Mybatis Generator allows you to create a single table with mybatis generator (or write your own template). However, these tools will not be able to create new fields during project development. I have to write the new fields to my existing SQL. It’s a painful process, especially if you repeat it many times.
Mybatis single table operation is also troublesome, because the filter criteria can be various, so you have to write a lot of dynamic SQL to comply with the query criteria, which makes it difficult for me to concentrate on the business.
Whenever this happens, I miss Hibernate. Hibernate add field is very simple, single table operation is also very convenient. But I still don’t like using Hibernate, haha.
#####mybatis-plus
And mybatis- Plus such a framework, a set of MyBatis and Hibernate advantages together framework. It provides the convenience of Hibernate’s single table CRUD operation while retaining the features of Mybatis.
Here’s what the official explanation for Mybatis plus is:
- 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.
- Our vision is to be
Mybatis
The best partner, likeContra GameIn 1P, 2P, gay friends collocation, efficiency doubled.
Bring questions to study, please think
- Mybatis – Plus how to implement single table URUD operation?
- What is the underlying implementation principle of Mybatis – Plus?
- What are the advantages of Mybatis – Plus over other frameworks like MyBatis Helper?
- How to integrate Mybatis – Plus to quickly build a Spring Boot project.
features
As you can see from the image above, MyBatis plus not only encapsulates basic CRUD operations, but also has built-in ANTI-SQL injection operations, common paging plug-ins, and my favorite ActiveRecord mode.
Anyone who has used JFinal knows what ActiveRecord is. Active Record is a data access design pattern that helps you map data objects to relational databases.
Common entity annotations
MP encapsulates common CRUD operations through ORM mode, and of course there are entity annotations. Let’s take a look at the annotations
The entity without annotation setting can be handled as follows:
- No annotation processing is required when the database table field name is humped.
- Or global configuration: Underline name dbColumnUnderline set true, uppercase isCapitalMode set true
In fact, I never wrote these notes by hand. I used the MP code generator to automatically generate the body and directly overwrite the original one, reducing manual error and making it easy and quick. As for @version and @keysequence annotations, I don’t think I’ve ever used them. Heh heh…
To simplify the CRUD
As mentioned above, MP has simplified the basic operation of single table in Mybatis. Let’s have a look first.
I prefer ActiveRecord to both because I don’t need to inject userMapper, I just call the method after new an object.
Complex queries are also simple. Create an EntityWrapper as the query object. The Wrapper interface encapsulates many common methods. Almost any condition that SQL can write can be expressed by calling the Wrapper method.
Architecture principles
Refer to the answer briefly.
But I suggest you go to the mp website or here, haha -> Mybatis -plus practice and architecture principle.pdf
Mybatis Plus code Generator with Mybatis Generator
Speaking of the mybatis Plus code generator code, I remember it was introduced in this article earlier
- The open source project Spring-Shro-Training mind map makes the project no longer difficult to understand
Now let’s use it again. The principle is simple: define a Velocity template (of course you can also customize it) and pass the parameters to render the template to generate the corresponding file.
I recommend that you do not directly overwrite the original file, you may have made changes, direct overwrite will cause loss.
The code generated by mybatis Generator is the basic add, delete, change, query and entity. The template seems to be unchangeable and obviously not flexible enough.
Mp plug-in extension
Mp not only helps us to implement the basic add, delete, change and check operations, but also extends many practical plug-ins. Make the development process easier.
The ##### paging plug-in follows these steps:
- Custom query statement paging (write your own SQL /mapper)
- Spring injects the MyBatis configuration paging plug-in
<plugins> <! - | paging plug-in configuration | plug-in provides two dialects choice: 1, 2, custom default dialect dialect implementation class, both not configured will throw an exception! Total number of pages | overflowCurrent overflow, set up the first page by defaultfalse| optimizeType Count optimization methods (version 2.0.9 changed to use jsqlparser don't need to configure) | -- - > <! - pay attention!!!!! If you want to support the second level cache pages using class CachePaginationInterceptor default, are as follows!!!!! --> <plugin interceptor="com.baomidou.mybatisplus.plugins.PaginationInterceptor">
<property name="sqlParser" ref="Custom parse class, can not" />
<property name="localPage" value=Default false to true to enable pageHeper support />
<property name="dialectClazz" value="Custom dialect class, can not" />
</plugin>
</plugins>
Copy the code
/ / Spring boot way @ EnableTransactionManagement @ Configuration @ MapperScan ("com.baomidou.cloud.service.*.mapper*"Public class MybatisPlusConfig {/** ** PaginationInterceptor public PaginationInterceptorpaginationInterceptor() {
returnnew PaginationInterceptor(); }}Copy the code
- Usermapper.java method content
Public interface UserMapper{// Can inherit or not inherit BaseMapper /** * <p> * </p> * * @param page * page-turning object, can be directly used as an XML parameter, pass the parameter page is automatic page-turning * @param state * state * @return
*/
List<User> selectUserList(Pagination page, Integer state);
}
Copy the code
- Userservicepl. Java invokes the page-turning method, requiring page.setRecords to be passed back to the page
public Page<User> selectUserPage(Page<User> page, Integer state) {
return page.setRecords(userMapper.selectUserList(page, state));
}
Copy the code
- Usermapper. XML is equivalent to writing a normal list query, and Mybatis – Plus automatically pages it for you
<select id="selectUserList" resultType="User">
SELECT * FROM user WHERE state=#{state}
</select>
Copy the code
##### Logical deletion plug-in
SQL > delete LogicNotDeleteValue = LogicNotDeleteValue default value Update tbl_xxx set “logicDeleteValue” = “default value”
The configuration is as follows:
- Change the integration global injector to LogicSqlInjector
@Bean
public GlobalConfiguration globalConfiguration() {
GlobalConfiguration conf = new GlobalConfiguration(new LogicSqlInjector());
conf.setLogicDeleteValue("1");
conf.setLogicNotDeleteValue("1");
conf.setIdType(2);
return conf;
}
Copy the code
- Application. Yml Global injected value: logicDeleteValue logicNotDeleteValue logicNotDeleteValue logicNotDeleteValue
mybatis-plus:
mapper-locations: classpath:/mapper/*Mapper.xml
# Entity scan, separate multiple packages with commas or semicolons
typeAliasesPackage: com.baomidou.springboot.entity
typeEnumsPackage: com.baomidou.springboot.entity.enums
global-config:
SQL > select * from user where ID = 1; SQL > select * from user where ID = 1;
id-type: 2
# field policy 0:" ignore judgment ",1:" non-null judgment "),2:" non-null judgment"
field-strategy: 2
db-column-underline: true
Delete the configuration
logic-delete-value: 0
logic-not-delete-value: 1
sql-injector: com.baomidou.mybatisplus.mapper.LogicSqlInjector
Copy the code
- Logically deleted fields require an annotation @tablelogic
@TableName("tbl_user") public class UserLogicDelete { private Long id; . @TableField(value ="delete_flag")
@TableLogic
private Integer deleteFlag;
}
Copy the code
An excellent example of Spring integration with Mybatis – Plus
-
Basic integration case mybatisplus-Spring-boot
-
Java EE (J2EE) rapid development framework SpringWind
-
SSM back-office framework KangarooAdmin
-
JAVA distributed rapid development base platform iBase4J
-
Another SSM background management framework framework
-
Maoning Morning Public Welfare Mall Morning
-
Simple and practical permission system Spring-shro-training Shiro case
The last
Welcome to follow the Java mind map public account, reply “Mind map” to download the source map file in the article. Mind mapping Java, make Java no longer difficult.