Mybatis-Plus is used as ORM framework to operate database in Matrix-Web project. The ORM frameworks commonly used in the market include Hibernetes, MyBatis, JPA, etc., so why choose MyBatis -Plus? Mainly based on the following considerations:
- Compatible with Mybatis, you can easily write very complex SQL and business logic. ^_^
- Simple, easy to use, single table operation does not need to write MYbatis XML, code automatically generated, can achieve rapid development.
- Based on Mybatis, fully compatible with Mybatis, this framework has no performance loss compared to Mybatis (claimed to be the best partner of Mybatis)
- Mybatis-Plus conforms to the development habits of Chinese people
- 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. In line with the purpose of this project.
Mybatis 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
The structure of Mybatis is as follows:
The above part comes from the official website.
Mybatis-Plus code generation
Myatis-Pluss is on the basis of MyBatis only do enhancement do not change, in order to simplify the development, improve efficiency. In line with the purpose of rapid development of back-end management system of this project. Mybatis-Plus provides a plug-in to generate code, which can read the table in the database, generate the corresponding entity class, Mapper class, WRITE SQL XML, Service class, etc. Mapper class and Service class have the ability to operate a single table CRUD, do not need to write additional SQL statements. For complex multi-table operations, you still need to write SQL statements.
Preparing SQL statements
In the areIS database, prepare the following sys_user table data as follows:
DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'User number'.`user_id` varchar(50) NOT NULL COMMENT 'Username'.`password` varchar(80) NOT NULL COMMENT 'Password, encrypted storage required'.`realname` varchar(20) DEFAULT NULL COMMENT 'Real Name'.`type` tinyint(3) DEFAULT '0' COMMENT 'Type,1 Administrator 2. Employee 3. Common User'.`mobile` varchar(30) DEFAULT NULL COMMENT 'Mobile phone Number'.`email` varchar(50) DEFAULT NULL COMMENT 'email'.`remarks` varchar(255) DEFAULT NULL COMMENT 'note'.`status` tinyint(1) DEFAULT '1' COMMENT '0 disable 1 Enable 2 Lock '.`avatar` varchar(255) DEFAULT NULL COMMENT 'User profile picture'.`create_time` datetime DEFAULT NULL COMMENT 'Registration Time'.`create_by` varchar(50) DEFAULT NULL COMMENT 'creator ID'.`update_time` datetime DEFAULT NULL COMMENT 'Update Time'.`update_by` varchar(50) DEFAULT NULL COMMENT 'Update person'.`sex` int(2) DEFAULT '1',
PRIMARY KEY (`id`),
KEY `USERNAME_IDX` (`user_id`),
KEY `REALNAME_IDX` (`realname`),
KEY `idx_mobile` (`mobile`))ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='users';
Copy the code
Add dependencies for generated code
The code generation module of matrix-Web project is matrix-gen-code. Add code generation dependencies to the project POM file, including mysql-connector-Java database dependency, mybatis-plus-generator, template engine dependency, code as follows:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.1</version>
</dependency>
Copy the code
Generated code logic
Mybatis-Plus code generation logic is relatively simple, directly posted source code, no longer explain.
public class MysqlGenerator {
public static String[] tableNames={"sys_user"};
public static String packageName="io.github.forezp.modules.system";
/** * RUN THIS */
public static void main(String[] args) {
// Code generator
AutoGenerator mpg = new AutoGenerator();
// Global configuration
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/generator-code/src/main/java");
gc.setAuthor("forezp");
gc.setOpen(false);
gc.setDateType(DateType.ONLY_DATE);
gc.setFileOverride(true);
gc.setBaseColumnList(true);
gc.setBaseResultMap(true);
gc.setServiceName("%sService");
mpg.setGlobalConfig(gc);
// Data source configuration
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("JDBC: mysql: / / 127.0.0.1:3306 / Aries? useUnicode=true&characterEncoding=utf8&tinyInt1isBit=false&useSSL=false&serverTimezone=GMT");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
mpg.setDataSource(dsc);
// Package configuration s
PackageConfig pc = new PackageConfig();
// pc.setModulename (scanner(" module name "));
pc.setParent(packageName);
pc.setController("controller");
pc.setEntity("entity");
mpg.setPackageInfo(pc);
// Custom configuration
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap(a) {
// to do nothing}}; List<FileOutConfig> focList =new ArrayList<>();
focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
@Override
public String outputFile(TableInfo tableInfo) {
// Customize the input file name
return projectPath + "/generator-code/src/main/resources/mapper/" + pc.getModuleName()
+ "/" + tableInfo.getEntityName() + "Mapper"+ StringPool.DOT_XML; }}); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); mpg.setTemplate(new TemplateConfig().setXml(null));
// Policy configuration
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setSuperEntityClass("io.github.forezp.common.base.BaseEntity");
strategy.setEntityLombokModel(true);
strategy.setCapitalMode(true);
strategy.setEntitySerialVersionUID(true);
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setInclude(tableNames);// Change the table name to the one you need
// strategy.setSuperControllerClass("io.github.forezp.modules.common.BaseController");
strategy.setSuperEntityColumns("id"."create_by"."create_time"."update_by"."update_time");
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
// Select freemarker engine to specify the following addition, note that poM dependencies must have!
mpg.setTemplateEngine(newFreemarkerTemplateEngine()); mpg.execute(); }}Copy the code
Run the Main method of the above code to generate the entity classes SysUser, SysUserMapper, SysUserService, SysUserServiceImpl, SysuserMapper. XML, SysUserController, The code is not going to be shown here.
Spring Boot integrates Mybatis-Plus
Matrix-web-backend is a back-end code module of matrix-Web. Matrix-web-backend is a Spring Boot project. Now we will explain how to introduce Mybatis-Plus in Spring Boot. It should be noted that matrix-Web backend uses Sharing-JDBC, Druid and Mybatis-Plus components as the framework for operating the database. This article describes how to integrate Mybatis-Plus with Spring Boot. Future articles will cover Sharing-JDBC and Druid.
Introduce the starting dependency of Mybatis-Plus in the poM file of the project, version 3.1.2, code is as follows:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatisplus.spring.boot.version}</version>
</dependency>
Copy the code
In the project profile appliaction. Yml mybatis – plus related configuration, including the datasource for a data source, mapper – is the configuration of the locations in the store mapper. The location of the XML, TypeAliasesPackage configures the package address of the entity class, among other configurations, as described in the code comments. All configurations are as follows:
mybatis-plus:
datasource: dataSource
mapper-locations: classpath:/mapper/*Mapper.xml
# Entity scan, separate multiple packages with commas or semicolons
typeAliasesPackage: io.github.forezp.modules.system.entity
typeEnumsPackage: io.github.forezp.modules.system.entity.enums
global-config:
db-config:
id-type: id_worker
capital-mode: true
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
# Hump underline conversion
db-column-underline: true
# Refresh mapper debugger
refresh-mapper: true
# database uppercase underline conversion
#capital-mode: true
# sequence interface implements class configuration
#key-generator: com.baomidou.springboot.xxx
Delete the configuration
logic-delete-value: 0
logic-not-delete-value: 1
# Custom fill policy interface implementation
# meta-object-handler: com.baomidou.springboot.xxx
# Customize SQL injectors
#sql-injector: com.baomidou.springboot.xxx
configuration:
map-underscore-to-camel-case: true
cache-enabled: false
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
Copy the code
In SpringBootServletInitializer springBoot project startup file configuration Mybtis MapperScan package name, configure the Mapper will automatically scan, and injected into the spring ioc container. The code is as follows:
@SpringBootApplication
@MapperScan({"io.github.forezp.modules.system.mapper" ,"io.github.forezp.modules.task.mapper"."io.github.forezp.modules.activiti.mapper"."io.github.forezp.modules.personnel.mapper"})
public class AriesApplication extends SpringBootServletInitializer {
public static void main(String[] args) { SpringApplication.run(AriesApplication.class, args); }}Copy the code
Place the code automatically generated in the previous section, SysUser, SysUserMapper, SysUserService, SysUserServiceImpl, SysuserMapper. XML, SysUserController, under the relevant packages, The SpringBoot project is started. So Spring Boot integration mybatis-plus integration is good.
conclusion
This article focuses on using Mybatis-Plus to generate code, and then shows you how to integrate Mybatis-Plus with Spring Boot. The next article will show you how to use Mybatis-Plus’s auto-fill and pagination features.
Participating Information:
Mp.baomidou.com/guide/# features
Download the source code
Github.com/forezp/matr…