哈喽!大家好,我是一位上进心十足,拥有极强学习力的在校大学生
我所写的博客的领域是面向后端技术的学习,未来会持续更新更多的【后端技术】以及【学习心得】。 偶尔会分享些前端基础知识,会更新实战项目,以及开发应用!
❤️❤️❤️ 感谢各位大可爱小可爱! ❤️❤️❤️
在我们开发项目的时候,最烦的也是最累的就是手码代码了,那么就不可以自己生成代码吗?作者今天给大家带来的就是如何利用mybatis-Plus自动生成代码,且配置成自己想要的效果出来。
回想我们之前进行开发的过程,首先我们需要编写与数据库表对应的实体类,接着再进行创建各种层次的包(mapper,service,impl),这个过程是不是感觉特别漫长呢,而现在一款神器登场了,它就是:myBatis-Plus的代码自动生成器。
官网链接:https://baomidou.com/pages/779a6e/#%E4%BD%BF%E7%94%A8
1.新建数据库表格
CREATE TABLE `sys_user` (
`id` int NOT NULL AUTO_INCREMENT COMMENT '用户id',
`username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_turkish_ci DEFAULT NULL COMMENT '用户名',
`nickname` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_turkish_ci DEFAULT NULL COMMENT '昵称',
`password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_turkish_ci DEFAULT NULL COMMENT '密码',
`sex` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_turkish_ci DEFAULT '男' COMMENT '性别',
`address` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_turkish_ci DEFAULT NULL COMMENT '地址',
`phone` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_turkish_ci DEFAULT NULL COMMENT '电话',
`email` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_turkish_ci DEFAULT NULL COMMENT '邮箱',
`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '用户注册的时间',
`role` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_turkish_ci DEFAULT 'USER' COMMENT '身份,1为管理员,USER为普通用户',
`avatar_url` varchar(255) COLLATE utf8mb4_turkish_ci DEFAULT NULL COMMENT '头像',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=42 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_turkish_ci COMMENT='用户列表';
数据库结构如下:
2.SpringBoot项目搭建
选择新建一个模块
然后选择Spring Initializr,按照图片标注的样式进行勾选。
重点!!!java选择版本8!!
点击进行下一步
SpringBoot尽量选择低版本,防止后面依赖出现问题,依赖项选择以上几个,有添加的直接加进去就可以了。其中Lombok是简化代码的工具,就是说加上@Data就可以不用写get和set了,具体效果如图:
然后就会看见一个名为Pom.xml的家伙
在pom.xml里面加入以下额外的依赖
com.baomidou
mybatis-plus-boot-starter
3.0.5
com.baomidou
mybatis-plus-generator
3.0.5
org.apache.velocity
velocity-engine-core
2.2
这里建议在结尾加上阿里云的库链接,导入依赖更加快速
nexus-aliyun
nexus-aliyun
http://maven.aliyun.com/nexus/content/groups/public/
true
false
public
aliyun nexus
http://maven.aliyun.com/nexus/content/groups/public/
true
false
以上就是SpringBoot的搭建过程
将我们的application的后缀改为yml,在里面配置我们的数据库
server:
port: 9090
ip: localhost
# ip: 47.108.165.96
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/room?
username: root
password: 123456
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
files:
upload:
path: E:\Vue项目\RoomSystem\Room\files\
# path: /root/files/
#alipay:
# appId: 2021000121698632
# appPrivateKey: MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCeTmUs8VNSl3hOHeP4Z6hG8FysBpQ+ZYsnBcYC/cX2M8uUZ9wLKbWrONsAeF1saR0bFaVZjhBAHVawY+6ncQGqfceGWw15UMrq2febVAPuI7ZY2zLA6y6mSlb7s+RA/3TNpAZE/qF0+l17TVEzRme3sjYwJuJu+HSucZSi5qZSSQ3RTqagtFkp8U2nfqjaAWen1FMsX3oiZK3crB3r4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l6gV4SpNlF5i0p6EoHFWHk01Dw3LjRv/TP3ZbsgvMWY74dURqFZGAQfPV9+urYzppFeZ8uQUErNRpWSIvVH4/Z/Hly4On/CR3gF8MUws4pZqWxIA5AoGAFwTJUf920O2Pi8f6KMuNVzZyZi/4eq7iTfkDirGFLKnLz9nuZviFJ/8iLswjptv05C8lHyxcOVG0hJo2Kvf2D0eKn6f1iVqeg3eTMCFwev7+YAMcHo/z8tSmfCMeiUwni0wPQaZwHaR8pkXkeNkQt6j3RERWQy1vuPM8TdN19ww=
# alipayPublicKey: MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5pxReorutulL54ha3s5gZrc9C/LzTqNElwV9/UkfUjks9Dhian1D3q987c8T9qbodEtbD6M9UGodEpda5pg7W8bkkK5cxpekjXmTNJKqIS1K51fyFhzoNCPJJ9G4HpqOtVz7QP2QF9RzCQpujj1/uwUsdsGG4kdYl+I5sJpersyPA53/2tfNgvk20urV8scSopisRKTRkWLDg77uT8RRZrRVSsZS7l2nktWYIz2aF/Gn7TnhTq4tyt6gKfulcDjIGhmo1w6huVX4pG7kmiM4EoiqaOqq8tt1kjMz+0dGGH44PYycTx0msSxoKm0uYLPHeoGttig7Lfs3pS8Q09n3lQIDAQAB
# notifyUrl: http://q5s98k.natappfree.cc/alipay/notify
构建一个名为CodeGenerator的Java类,然后直接copy官网代码修改成自己的:
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import java.util.Collections;
/**
* mp代码生成器
*/
public class CodeGenerator {
public static void main(String[] args) {
generate();
}
private static void generate() {
FastAutoGenerator.create("jdbc:mysql://localhost:3306/xhc?serverTimezone=GMT%2b8", "root", "123456")
.globalConfig(builder -> {
builder.author("") // 设置作者
.enableSwagger() // 开启 swagger 模式
.fileOverride() // 覆盖已生成文件
.outputDir("E:\\Vue项目\\B站\\后台管理系统\\springboot\\src\\main\\java\\"); // 指定输出目录
})
.packageConfig(builder -> {
builder.parent("com.example.springboot") // 设置父包名
.moduleName("") // 设置父包模块名
.pathInfo(Collections.singletonMap(OutputFile.mapperXml, "E:\\Vue项目\\B站青戈\\后台管理系统\\springboot\\src\\main\\resources\\mapper\\")); // 设置mapperXml生成路径
})
.strategyConfig(builder -> {
builder.entityBuilder().enableLombok();
// builder.mapperBuilder().enableMapperAnnotation().build();
builder.controllerBuilder().enableHyphenStyle() // 开启驼峰转连字符
.enableRestStyle(); // 开启生成@RestController 控制器
builder.addInclude("sys_menu") // 设置需要生成的表名
.addTablePrefix("t_", "sys_"); // 设置过滤表前缀
})
// .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
.execute();
}
}
然后运行,生成如下的结果:
直接生成了User表的全部代码
打开controller.java.vm,修改里面的内容。
package ${package.Controller};
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
import ${package.Service}.${table.serviceName};
import ${package.Entity}.${entity};
#if(${restControllerStyle})
import org.springframework.web.bind.annotation.RestController;
#else
import org.springframework.stereotype.Controller;
#end
#if(${superControllerClassPackage})
import ${superControllerClassPackage};
#end
/**
*
* $!{table.comment} 前端控制器
*
*
* @author ${author}
* @since ${date}
*/
#if(${restControllerStyle})
@RestController
#else
@Controller
#end
@RequestMapping("#if(${package.ModuleName})/${package.ModuleName}#end/#if(${controllerMappingHyphenStyle})${controllerMappingHyphen}#else${table.entityPath}#end")
#if(${kotlin})
class ${table.controllerName}#if(${superControllerClass}) : ${superControllerClass}()#end
#else
#if(${superControllerClass})
public class ${table.controllerName} extends ${superControllerClass} {
#else
public class ${table.controllerName} {
#end
@Resource
private ${table.serviceName} ${table.entityPath}Service;
//新增或者更新
@PostMapping
public Result save(@RequestBody ${entity} ${table.entityPath}) {
${table.entityPath}Service.saveOrUpdate(${table.entityPath});
return Result.success();
}
//删除
@DeleteMapping("/{id}")
public Result delete(@PathVariable Integer id) {
${table.entityPath}Service.removeById(id);
return Result.success();
}
@PostMapping("/del/batch")
public Result deleteBatch(@RequestBody List ids) {//批量删除
${table.entityPath}Service.removeByIds(ids);
return Result.success();
}
//查询所有数据
@GetMapping
public Result findAll() {
return Result.success(${table.entityPath}Service.list());
}
@GetMapping("/{id}")
public Result findOne(@PathVariable Integer id) {
return Result.success(${table.entityPath}Service.getById(id));
}
@GetMapping("/page")
public Result findPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize) {
QueryWrapper<${entity}> queryWrapper = new QueryWrapper<>();
queryWrapper.orderByDesc("id");
return Result.success(${table.entityPath}Service.page(new Page<>(pageNum, pageSize), queryWrapper));
}
}
#end
效果:
以上就是对Mybatis-Plus自动生成代码,自定义Controller简单的概述,使得我们的项目开发周期大大缩短,提供了足够的时间来进行我们的项目优化!
如果这篇文章有帮助到你,希望可以给作者点个赞,创作不易,如果有对后端技术、前端领域感兴趣的,也欢迎关注 ,我将会给你带来巨大的收获与惊喜!