用MybatisPlus代码生成器生成代码
作者简介
【特别注意】适用版本:mybatis-plus-generator 3.5.1 以下版本
一、创建Springboot项目
在之前的IDEA专栏中,已有文章,就不另外说明了。
二、导入相关依赖
打开pom.xml 填入以下依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.30</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
</dependency>
三、拉代码生成器代码
直接到 注意的地方:
- 全局配置里面的路径
- 数据源的配置
- 包配置里面的模块配置(默认配置也可以修改)
pc.setParent("com.wms")
.setEntity("entity")
.setMapper("mapper")
.setService("service")
.setServiceImpl("service.impl")
.setController("controller");
- 策略配置里面父类相关可以删除
四、配置数据库连接 yml
server:
port: 8090
spring:
datasource:
url: jdbc:mysql://localhost:3306/ming?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
driver-class-name: com.mysql.jdbc.Driver
username: root
password: root
Logging:
level:
com.wms: debug
五、建表
DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 主键, `no` varchar(20) DEFAULT NULL COMMENT 账号, `name` varchar(100) NOT NULL COMMENT 名字, `password` varchar(20) NOT NULL COMMENT 密码, `age` int(11) DEFAULT NULL, `sex` int(11) DEFAULT NULL COMMENT 性别, `phone` varchar(20) DEFAULT NULL COMMENT 电话, `role_id` int(11) DEFAULT NULL COMMENT 角色 0超级管理员,1管理员,2普通账号, `isValid` varchar(4) DEFAULT Y COMMENT 是否有效,Y有效,其他无效, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
六、生成代码
- 右键代码生成器类,点击执行,在终端控制台输入对应的表名
- 输完后按回车键,效果如下
- 代码生成如下,自动给我们生成了对应的controller、entity、mapper、service、serviceImpl代码。
七、编写测试代码运行
- 修改UserController代码
package com.springboot.demo.controller;
import com.springboot.demo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* <p>
* 前端控制器
* </p>
*
* @author 明哥
* @since 2022-10-30
*/
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private IUserService userService;
@GetMapping("listAll")
public List listAll(){
return userService.list();
}
}
- 检查UserMapper是否缺个注解
- 启动服务
- 浏览器验证 输入地址:http://localhost:8090/user/listAll
- 在数据库插入一条数据试试
