1.What’s up Mybatis Plus?
MyBatis-Plus (opens new window)(abbreviation MP) Is a MyBatis (opens new window)enhancement tools in MyBatis On the basis of only enhancements without changes, it was born to simplify development and improve efficiency.
characteristic
- No intrusion:Only enhancements are made without changes. Introducing it will not affect the existing project and is as smooth as silk.
- Low loss:Basics will be automatically injected upon startup CURD, Basically no loss in performance, direct object-oriented operation
- powerful CRUD operate:Built-in universal Mapper、 Universal Service, Most of the single table can be implemented with only a small amount of configuration CRUD Operations, and more powerful conditional constructors to meet various usage needs
- support Lambda formal call:pass Lambda Expressions make it easy to write various query conditions without worrying about mistyping fields.
- Support automatic generation of primary keys:Supports up to 4 primary key strategies (including distributed unique ID Builder — Sequence), Freely configurable to perfectly solve the primary key problem
- support ActiveRecord model:support ActiveRecord Formal calls, entity classes only need to inherit Model class can perform powerful CRUD operate
- Support custom global common operations:Support global common method injection ( Write once, use anywhere )
- Built-in code generator:Use code or Maven Plug-ins can be quickly generated Mapper 、 Model 、 Service 、 Controller Layer code, support template engine, and many custom configurations waiting for you to use
- Built-in paging plugin:based on MyBatis For physical paging, developers do not need to care about the specific operations. After configuring the plug-in, writing paging is equivalent to ordinary List Inquire
- Pagination plug-in supports multiple databases:support MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer and other databases
- Built-in performance analysis plug-in:Exportable SQL statement and its execution time. It is recommended to enable this function during development and testing to quickly identify slow queries.
- Built-in global interception plug-in:Provide full table delete 、 update Intelligent operation analysis and blocking, you can also customize interception rules to prevent misoperations
Support database
anything that can be used
MyBatis
conduct CRUD, and supports standards SQL The specific support status of the database is as follows. If you do not want to view the pagination tutorial in the list below PR your support.
- MySQL,Oracle,DB2,H2,HSQL,SQLite,PostgreSQL,SQLServer,Phoenix,Gauss ,ClickHouse,Sybase,OceanBase,Firebird,Cubrid,Goldilocks,csiidb,informix,TDengine,redshift
- Dameng Database, Xugu Database, Renmin University Jincang Database, Nanda General (Huaku )Database, NTU General Database, Shentong Database, Hangao Database, Youxuan Database, Xingruige Database
2.mysql Environmental preparation
mysql database
docker run --name docker-mysql -e MYSQL_ROOT_PASSWORD=123456 -p 3306:3306 -d mysql
Initialization data
create database demo;
create table user_info
(
user_id varchar(64) not null primary key,
username varchar(100) null ,
age int(3) null ,
gender tinyint(1) null ,
remark varchar(255) null ,
create_time datetime null ,
create_id varchar(64) null ,
update_time datetime null ,
update_id varchar(64) null ,
enabled tinyint(1) default 1 null
);
illustrate
msyql username:root
mysql password: 123456
3.code engineering
Experiment purpose: use mybatis plus operate mysql database
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springboot-demo</artifactId>
<groupId>com.et</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>mybatis-plus</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
</dependencies>
</project>
application.yaml
server:
port: 8088
spring:
datasource:
password: 123456
username: root
url: jdbc:mysql://localhost:3306/demo?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
driver-class-name: com.mysql.cj.jdbc.Driver
generator
package com.et.mybaties.plus.util;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class GeneratorCode {
/**
* database connect
* */
private static final String dbUrl = "jdbc:mysql://localhost:3306/demo?useUnicode=true&useSSL=false&characterEncoding=utf8";
/**
* username
* */
private static final String username = "root";
/**
* pasword
* */
private static final String password = "123456";
/**
* moduleName
* */
private static final String moduleName = "/mybatis-plus";
/**
* <p>
* read console content
* @param
* </p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("please input:" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotBlank(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("please right conntent:" + tip + "!");
}
public static void main(String[] args) {
// Code Generateor
AutoGenerator mpg = new AutoGenerator();
String module = scanner("please input module");
// GlobalCOnfig
GlobalConfig gc = new GlobalConfig();
//D:\IdeaProjects\ETFramework
String basedir ="D:/IdeaProjects/ETFramework/";
String projectPath = basedir+moduleName;
System.out.println(projectPath);
//OutputDir
gc.setOutputDir(projectPath+"/src/main/java");
gc.setAuthor("stopping");
//some generate rule
gc.setMapperName("%sMapper");
gc.setServiceName("%sService");
gc.setServiceImplName("%sServiceImp");
gc.setControllerName("%sController");
gc.setXmlName("%sMapper");
gc.setIdType(IdType.AUTO);
gc.setOpen(false);
//IsOverride
gc.setFileOverride(true);
//isSwagger2
gc.setSwagger2(false);
mpg.setGlobalConfig(gc);
//datasource
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl(dbUrl);
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername(username);
dsc.setPassword(password);
mpg.setDataSource(dsc);
// PackageConfig
PackageConfig pc = new PackageConfig();
//package path
pc.setParent("com.et.mybaties.plus");
//subpackage path
pc.setMapper("mapper."+module);
pc.setController("controller."+module);
pc.setService("service."+module);
pc.setServiceImpl("service."+module+".imp");
pc.setEntity("model.entity");
pc.setXml("Mapper");
mpg.setPackageInfo(pc);
//custom config
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// freemarker
String templatePath = "/templates/mapper.xml.ftl";
// FileOutConfig
List<FileOutConfig> focList = new ArrayList<>();
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// Mapper
String xmlUrl = projectPath + "/src/main/resources/mapper/" + module
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
System.out.println("xml path:"+xmlUrl);
return xmlUrl;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// templateConfig
TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// StrategyConfig
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
// common file
//strategy.setSuperEntityColumns("id");
strategy.setInclude(scanner("tablename,multi can be seperated ,").split(","));
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
//isAnnotationEnable
strategy.setEntityTableFieldAnnotationEnable(true);
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
run main function, the corresponding code generated is as follows
DemoApplication.java
package com.et.mybaties.plus;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.et.mybaties.plus.mapper")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
The above are just some key codes. For all codes, please see the code repository below.
code repository
4.test
Write test classes to perform insert, update, and custom query tests
package com.et.mybaties.plus;
import com.et.mybaties.plus.model.entity.UserInfo;
import com.et.mybaties.plus.service.userInfo.UserInfoService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApplication.class)
public class DemoTests {
private Logger log = LoggerFactory.getLogger(getClass());
@Autowired
UserInfoService userInfoService;
@Before
public void before() {
log.info("init some data");
}
@After
public void after(){
log.info("clean some data");
}
@Test
public void query() {
log.info("your method test Code");
userInfoService.lambdaQuery().list().forEach(System.out::println);
}
@Test
public void testQueryWrapper() {
log.info("your method test Code");
userInfoService.testQueryWrapper(3).forEach(System.out::println);
}
@Test
public void insert() {
log.info("your method test Code");
for(int i =1;i<10;i++) {
UserInfo ui = new UserInfo();
ui.setUserId(i+"id");
userInfoService.removeById(i+"id");
ui.setUsername("HBLOG"+i);
ui.setAge(i);
userInfoService.save(ui);
}
}
}