One. brief introduction
MyBatis plus (opens new window) (MP for short) is an enhancement tool of MyBatis (opens new window). Based on MyBatis, it only makes enhancement without change, and is born to simplify development and improve efficiency.
characteristic:
- No invasion: it is only enhanced without change, and its introduction will not affect the existing project, which is as smooth as silk
- Low loss: the basic CURD will be injected automatically upon startup, with basically no loss of performance and direct object-oriented operation
- Powerful crud operation: built in general Mapper and general Service, most CRUD operations of a single table can be realized only through a small number of configurations, and there is a powerful condition constructor to meet various use requirements
- Support Lambda formal call: it is convenient to write various query conditions through Lambda expression, and there is no need to worry about wrong fields
- Support automatic generation of primary key: support up to 4 primary key strategies (including distributed unique ID generator - Sequence), which can be configured freely to perfectly solve the primary key problem
- Support ActiveRecord mode: support ActiveRecord formal calls. Entity classes only need to inherit Model classes to perform powerful CRUD operations
- Support custom global general operations: support global general method injection (Write once, use anywhere)
- Built in code generator: code or Maven plug-in can be used to quickly generate Mapper, Model, Service and Controller layer code, support template engine, and have more custom configurations for 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, writing paging is equivalent to ordinary List query
- The paging plug-in supports multiple databases: MySQL, MariaDB, Oracle, DB2, H2, HSQL, SQLite, Postgre, SQLServer and other databases
- Built in performance analysis plug-in: it can output 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: it provides intelligent analysis and blocking of full table delete and update operations, and can also customize interception rules to prevent misoperation
Official API document address: https://mp.baomidou.com/guide/#%E7%89%B9%E6%80%A7
II. Database preparation
The mysql database is used here. The database name is storeprocedure and the data table name is student_info:
SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for student_info -- ---------------------------- DROP TABLE IF EXISTS `student_info`; CREATE TABLE `student_info` ( `id` int(11) NOT NULL, `name` varchar(15) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL, `age` int(3) NULL DEFAULT NULL, `sex` varchar(2) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL, `create_time` datetime(0) NULL DEFAULT NULL, `create_by` varchar(15) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL, `update_time` datetime(0) NULL DEFAULT NULL, `update_by` varchar(15) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of student_info -- ---------------------------- INSERT INTO `student_info` VALUES (1, 'Zhang San', 20, 'male', '2021-06-16 16:26:12', 'administrator', NULL, NULL); INSERT INTO `student_info` VALUES (2, 'Li Si', 20, 'male', '2021-06-23 16:26:15', 'administrator', NULL, NULL); INSERT INTO `student_info` VALUES (3, 'Wang Wu', 21, 'male', '2021-06-22 16:26:26', 'administrator', NULL, NULL);
Three. Project construction
1. First in POM The main dependencies of introducing mybatis plus into the XML file are as follows:
<!-- mybatis-plus combination springboot rely on --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.1</version> </dependency> <!-- mybatis-plus Main dependence --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>3.4.1</version> </dependency> <!-- Velocity((default) template engine dependency --> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.3</version> </dependency>
2. Code generator dependency:
<!-- Code generator dependency --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.4.1</version> </dependency>
3. Complete POM XML file content:
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.2.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>mybatisplus-demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>mybatisplus-demo</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <!---Swagger2 Online document configuration--> <!--swagger Not supported by itself spring mvc of springfox hold swagger Wrapped it up so that he can support it springmvc--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.6.1</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.6.1</version> </dependency> <!-- Code generator dependency --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.4.1</version> </dependency> <!-- mybatis-plus combination springboot rely on --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.1</version> </dependency> <!-- mybatis-plus Main dependence --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>3.4.1</version> </dependency> <!-- Velocity((default) template engine dependency --> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.3</version> </dependency> <!-- mysql Database connection driver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>RELEASE</version> <scope>compile</scope> </dependency> <!-- lombok plug-in unit --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>RELEASE</version> <scope>compile</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
4. The code generator code is as follows:
package com.example.mybatisplusdemo; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.config.*; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; public class CodeGenerator { public static void main(String[] args) { // Code generator AutoGenerator mpg = new AutoGenerator(); // Global configuration GlobalConfig gc = new GlobalConfig(); // String projectPath = System.getProperty("user.dir"); String projectPath = "D:\\mybaitsplus_generation_code";//Code generation address gc.setOutputDir(projectPath + "/src/main/java"); gc.setAuthor("keson"); gc.setOpen(false); gc.setSwagger2(true); //Entity attribute Swagger2 annotation mpg.setGlobalConfig(gc); // Data source configuration DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/storeprocedure?useUnicode=true&useSSL=false&characterEncoding=utf8"); // dsc.setSchemaName("public"); dsc.setDriverName("com.mysql.cj.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("root"); mpg.setDataSource(dsc); // Package configuration PackageConfig pc = new PackageConfig(); pc.setModuleName(""); pc.setParent("com.example.mybatisplusdemo"); mpg.setPackageInfo(pc); // Policy configuration StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); // strategy.setSuperEntityClass("your own parent entity, no need to set it!"); strategy.setEntityLombokModel(true); strategy.setRestControllerStyle(true); // Public parent class // strategy.setSuperControllerClass("your own parent controller, you don't need to set it if you don't have it!"); // Public fields written in the parent class // strategy.setSuperEntityColumns("id"); strategy.setInclude("student_info".split(",")); strategy.setControllerMappingHyphenStyle(true); strategy.setTablePrefix(pc.getModuleName() + "_"); mpg.setStrategy(strategy); mpg.execute(); } }
5. The structure of the generated code is as follows:
6. Move the code into the project. The xml is generally placed in the resource directory. After sorting, the project structure is as follows:
7. Add @ MapperScan annotation in the startup class to scan the interface of Dao layer:
@SpringBootApplication @MapperScan("com.example.mybatisplusdemo.mapper") public class MybatisplusDemoApplication { public static void main(String[] args) { SpringApplication.run(MybatisplusDemoApplication.class, args); } }
8.application. The YML configuration file is as follows:
server: port: 8080 #Port number spring: application: name: mybatisplus-demo #Service name datasource: #Database connection information url: jdbc:mysql://localhost:3306/storeprocedure?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver #Address of xml file mybatis-plus: mapper-locations: classpath:xml/*.xml
9. Entity class StudentInfo Code:
@Data @EqualsAndHashCode(callSuper = false) @ApiModel(value="StudentInfo object", description="") public class StudentInfo implements Serializable { private static final long serialVersionUID = 1L; private Integer id; private String name; private Integer age; private String sex; private LocalDateTime createTime; private String createBy; private LocalDateTime updateTime; private String updateBy; }
10. Add @ Repository annotation on StudentInfoMapper interface:
@Repository public interface StudentInfoMapper extends BaseMapper<StudentInfo> { List<StudentInfo> listAll(); }
In studentinfomapper Implement the corresponding methods in the XML file:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.example.mybatisplusdemo.mapper.StudentInfoMapper"> <!-- General query result column --> <sql id="Base_Column_List"> id,name,age,sex,create_time,create_by,update_time,update_by </sql> <!-- Entity mapping column --> <resultMap id="Base_Result_Map" type="com.example.mybatisplusdemo.entity.StudentInfo"> <result column="id" property="id"/> <result column="name" property="name"/> <result column="age" property="age"/> <result column="sex" property="sex"/> <result column="create_time" property="createTime"/> <result column="create_by" property="createBy"/> <result column="update_time" property="updateTime"/> <result column="update_by" property="updateBy"/> </resultMap> <select id="listAll" resultMap="Base_Result_Map"> select <include refid="Base_Column_List"></include> from student_info </select> </mapper>
11.IStudentInfoService:
public interface IStudentInfoService extends IService<StudentInfo> { List<StudentInfo> listAll(); }
StudentInfoServiceImpl:
@Service public class StudentInfoServiceImpl extends ServiceImpl<StudentInfoMapper, StudentInfo> implements IStudentInfoService { @Autowired private StudentInfoMapper studentInfoMapper; @Override public List<StudentInfo> listAll() { return studentInfoMapper.listAll(); } }
12. StudentInfoController of controller layer:
@RestController @RequestMapping("/student-info") public class StudentInfoController { @Autowired private IStudentInfoService studentInfoService; @GetMapping("listAll") public List<StudentInfo> listAll(){ return studentInfoService.listAll(); } }
Four. Project operation
1. Start the project:
2. Use postman to access and test the interface. The data returned by the interface is successful:
Five. summary
This blog is just a general introduction to how SpringBoot integrates mybatis plus, so it only involves some simple teaching operations. Later, you can expand the code according to the corresponding business logic.
public interface BaseMapper<T> extends Mapper<T> { int insert(T entity); int deleteById(Serializable id); int deleteByMap(@Param("cm") Map<String, Object> columnMap); int delete(@Param("ew") Wrapper<T> queryWrapper); int deleteBatchIds(@Param("coll") Collection<? extends Serializable> idList); int updateById(@Param("et") T entity); int update(@Param("et") T entity, @Param("ew") Wrapper<T> updateWrapper); T selectById(Serializable id); List<T> selectBatchIds(@Param("coll") Collection<? extends Serializable> idList); List<T> selectByMap(@Param("cm") Map<String, Object> columnMap); T selectOne(@Param("ew") Wrapper<T> queryWrapper); Integer selectCount(@Param("ew") Wrapper<T> queryWrapper); List<T> selectList(@Param("ew") Wrapper<T> queryWrapper); List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> queryWrapper); List<Object> selectObjs(@Param("ew") Wrapper<T> queryWrapper); <E extends IPage<T>> E selectPage(E page, @Param("ew") Wrapper<T> queryWrapper); <E extends IPage<Map<String, Object>>> E selectMapsPage(E page, @Param("ew") Wrapper<T> queryWrapper); }
The project has been uploaded to the personal cloud disk, and interested partners can download it by themselves:
Link: https://pan.baidu.com/s/1ZFaygWztZgptGkGXMiL1nw
Extraction code: ty25