官网地址:https://mp.baomidou.com/
官网的原话,详细请看官网
MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
根据教程:【idea版】springcloud微服务(1)之多模块版本新建一个springcloud项目
创建一个子模块:springcloud-mybatisPlus-example
<?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>springcloud-example</artifactId> <groupId>org.example</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>springcloud-mybatisPlus-example</artifactId> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>2.3.5.RELEASE</version> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>11</source> <target>11</target> </configuration> </plugin> </plugins> </build> </project>
<!--mysql begin--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.22</version> </dependency> <!-- mysql end--> <!--mybatis--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.0</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.4.0</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-support</artifactId> <version>2.3</version> </dependency> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.2</version> </dependency>
在resources里新建文件application.yml
server: port: 8008 # 数据库设置 spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://192.168.56.121:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8 username: root password: 123456 # mybatis-plu设置 mybatis-plus: mapper-locations: classpath*:mapper/*Mapper.xml #扫描的xml文件路径 configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #控制台日志输出
mybatis有一个自动生产实体,serive,mapper接口类和mapper.xml文件的工具类(官网也有实例)
在test目录下创建一个CodeGenerator类
CodeGenerator类代码:
package generator; import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.core.toolkit.StringPool; 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.DateType; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine; import java.util.ArrayList; import java.util.List; public class CodeGenerator { public static void main(String[] args) { // 代码生成器 AutoGenerator mpg = new AutoGenerator(); // 全局配置 GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); gc.setOutputDir(projectPath + "/springcloud-mybatisPlus-example/src/main/java"); gc.setAuthor("binggoling"); gc.setOpen(false); gc.setEntityName("%sEntity"); gc.setBaseColumnList(true); gc.setBaseResultMap(true); gc.setDateType(DateType.ONLY_DATE); gc.setSwagger2(false); //实体属性 Swagger2 注解 mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/test?useSSL=false"); // dsc.setDriverName("dm.jdbc.driver.DmDriver"); //jdk 1.8使用这个 9之后就要下面的 dsc.setDriverName("com.mysql.cj.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("***"); dsc.setDbType(DbType.MYSQL); mpg.setDataSource(dsc); // 包配置 PackageConfig pc = new PackageConfig(); // pc.setModuleName(scanner("模块名")); pc.setParent("com.example"); mpg.setPackageInfo(pc); // 自定义配置 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { // to do nothing } }; // 如果模板引擎是 velocity String templatePath = "/templates/mapper.xml.vm"; // 自定义输出配置 List<FileOutConfig> focList = new ArrayList<>(); // 自定义配置会被优先输出 focList.add(new FileOutConfig(templatePath) { @Override public String outputFile(TableInfo tableInfo) { // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!! // return projectPath + "/src/main/resources/mapper/" + pc.getModuleName() // + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; return projectPath + "/springcloud-mybatisPlus-example/src/main/resources/mapper" + pc.getModuleName() + "/" + tableInfo.getEntityName().replace("Entity","") + "Mapper" + StringPool.DOT_XML; } }); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); // 配置模板 TemplateConfig templateConfig = new TemplateConfig(); // 配置自定义输出模板 //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别 templateConfig.setEntity("templates/entity.java"); // templateConfig.setService(); templateConfig.setController(null); templateConfig.setXml(null); mpg.setTemplate(templateConfig); // 策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); // strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!"); strategy.setEntityLombokModel(true); strategy.setRestControllerStyle(true); // 公共父类 // strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!"); // 写于父类中的公共字段 // strategy.setSuperEntityColumns("id"); strategy.setInclude("table1"); strategy.setControllerMappingHyphenStyle(true); strategy.setTablePrefix(pc.getModuleName() + "_"); mpg.setStrategy(strategy); mpg.setTemplateEngine(new VelocityTemplateEngine()); mpg.execute(); } }
准备一个数据库表:
SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for table1 -- ---------------------------- DROP TABLE IF EXISTS `table1`; CREATE TABLE `table1` ( `test1` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `test2` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `test3` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `test4` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `test5` int(255) NULL DEFAULT NULL ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of table1 -- ---------------------------- INSERT INTO `table1` VALUES ('1', '1', '1', '1', 1); INSERT INTO `table1` VALUES ('aa', 'ss', 'dd', 'ff', 2); INSERT INTO `table1` VALUES ('aa', 'ss', 'dd', 'ff', 3); SET FOREIGN_KEY_CHECKS = 1;
直接运行main方法,然后生产实体代码
生产之后的结果:
新建MybatisApplication.java
package com.example; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * @description: * @time: 2021/5/24 9:58 */ @SpringBootApplication public class MybatisApplication { public static void main(String[] args) { SpringApplication.run(MybatisApplication.class, args); } }
新建MybatisPlusConfig.java
package com.example.config; import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @description: * @time: 2021/3/22 10:41 */ @Configuration @MapperScan("com.example.mapper") public class MybatisPlusConfig { /** * 分页配置,不配不能使用分页 */ @Bean public MybatisPlusInterceptor mybatisPlusInterceptor(){ MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return interceptor; } }
package com.example.controller; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.example.entity.Table1Entity; import com.example.service.ITable1Service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** * @description: * @author: libingwei * @time: 2021/5/24 10:04 */ @RestController public class TestController { @Autowired private ITable1Service table1Service; @RequestMapping("/test") public String getA(){ return "success"; } @RequestMapping("/list") public String getList(){ return table1Service.list().toString(); } //分页查询 @RequestMapping("/listPage") public String getListPage(@RequestParam Integer page, @RequestParam Integer size){ IPage<Table1Entity> iPage = new Page<>(page, size); QueryWrapper<Table1Entity> queryWrapper = new QueryWrapper<>(); queryWrapper.lambda().eq(Table1Entity::getTest1,"1"); iPage = table1Service.page(iPage, queryWrapper); return iPage.getRecords().toString(); } }
http://localhost:9000/list
返回值:
[Table1Entity(test1=1, test2=1, test3=1, test4=1, test5=1), Table1Entity(test1=aa, test2=ss, test3=dd, test4=ff, test5=2), Table1Entity(test1=aa, test2=ss, test3=dd, test4=ff, test5=3)]