从零到一保姆级前后端分离权限系统
一、简单版
1、pom
<?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.5.9</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.stu</groupId>
<artifactId>study</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>study</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
</dependencies>
</project>
2、CodeGenerator.java
package com.stu.study.utils;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import java.util.Collections;
/******************************
* 用途说明:
* 作者姓名: 更多干货 公众号 程序员小明1024
* 创建时间: 2023-02-27 21:26
******************************/
public class CodeGenerator {
public static void main(String[] args) {
generate();
}
private static void generate(){
String projectPath = System.getProperty("user.dir");
FastAutoGenerator.create("jdbc:mysql://localhost:3306/2023Java?serverTimezone=GMT%2b8",
"root", "study")
.globalConfig(builder -> {
builder.author("技术从南指到北") // 设置作者
.enableSwagger() // 开启 swagger 模式
.fileOverride() // 覆盖已生成文件
.outputDir(projectPath + "/src/main/java"); // 指定输出目录"E:\\20221025_work\\2023JAVA\\src\\main\\java\\"
})
.packageConfig(builder -> {
builder.parent("com.stu.study") // 设置父包名
.moduleName("") // 设置父包模块名
.pathInfo(Collections.singletonMap(OutputFile.mapperXml,
projectPath + "/src/main/resources/mapper")); // 设置mapperXml生成路径
})
.strategyConfig(builder -> {
builder.entityBuilder().enableLombok();
builder.mapperBuilder().enableMapperAnnotation().build();
builder.controllerBuilder().enableHyphenStyle() // 开启驼峰转连字符
.enableRestStyle(); // 开启生成@RestController 控制器
builder.addInclude("sys_role") // 设置需要生成的表名
.addTablePrefix("sys_"); // 设置过滤表前缀
})
// .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
.execute();
}
}
3、controller.java.vm
注意目录,在resources下的templats文件夹下创建controller.java.vm文件

package ${package.Controller};
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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}
* 作者姓名: 更多干货 公众号 技术从南指到北
* 创建时间: ${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;
/******************************
* 用途说明: $!{table.comment}
* 作者姓名: 更多干货 公众号 技术从南指到北
* 创建时间: ${date}
******************************/
@PostMapping
public boolean save(@RequestBody ${entity} ${table.entityPath}){
return ${table.entityPath}Service.saveOrUpdate(${table.entityPath});
}
/******************************
* 用途说明: $!{table.comment}
* 作者姓名: 更多干货 公众号 技术从南指到北
* 创建时间: ${date}
******************************/
@DeleteMapping("/{id}")
public Boolean delete(@PathVariable Integer id){
return ${table.entityPath}Service.removeById(id);
}
/******************************
* 用途说明: $!{table.comment}
* 作者姓名: 更多干货 公众号 技术从南指到北
* 创建时间: ${date}
******************************/
@PostMapping("/del/batch")
public boolean deleteBatch(@RequestBody List<Integer> ids){
return ${table.entityPath}Service.removeByIds(ids);
}
/******************************
* 用途说明: $!{table.comment}
* 作者姓名: 更多干货 公众号 技术从南指到北
* 创建时间: ${date}
******************************/
@GetMapping
public List<${entity}> findAll(){
return ${table.entityPath}Service.list();
}
/******************************
* 用途说明: $!{table.comment}
* 作者姓名: 更多干货 公众号 技术从南指到北
* 创建时间: ${date}
******************************/
@GetMapping("/{id}")
public ${entity} findOne(@PathVariable Integer id){
return ${table.entityPath}Service.getById(id);
}
/******************************
* 用途说明: $!{table.comment}
* 作者姓名: 更多干货 公众号 技术从南指到北
* 创建时间: ${date}
******************************/
@GetMapping("/page")
public Page<${entity}> findPage(@RequestParam Integer pageNum,
@RequestParam Integer pageSize){
QueryWrapper<${entity}> queryWrapper=new QueryWrapper<>();
queryWrapper.orderByDesc("id");
return ${table.entityPath}Service.page(new Page<>(pageNum,pageSize),queryWrapper);
}
}
#end
4、mybatis puls配置类
package com.stu.study.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;
/******************************
* 用途说明:
* 作者姓名: 程序员小明1024
* 创建时间: 2023-02-09 22:02
******************************/
@Configuration
@MapperScan("com.stu.**.mapper")
public class MybatisPlusConfig {
/**
* 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
return interceptor;
}
}
5、目录结构
6、点击运行main方法,生成的代码如下
controller
package com.stu.study.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.stu.study.service.IRoleService;
import com.stu.study.entity.Role;
import org.springframework.web.bind.annotation.RestController;
/******************************
* 用途说明:
* 作者姓名: 更多干货 公众号 程序员小明1024
* 创建时间: 2023-02-27
******************************/
@RestController
@RequestMapping("//role")
public class RoleController {
@Resource
private IRoleService roleService;
/******************************
* 用途说明:
* 作者姓名: 更多干货 公众号 程序员小明1024
* 创建时间: 2023-02-27
******************************/
@PostMapping
public boolean save(@RequestBody Role role){
return roleService.saveOrUpdate(role);
}
/******************************
* 用途说明:
* 作者姓名: 更多干货 公众号 程序员小明1024
* 创建时间: 2023-02-27
******************************/
@DeleteMapping("/{id}")
public Boolean delete(@PathVariable Integer id){
return roleService.removeById(id);
}
/******************************
* 用途说明:
* 作者姓名: 更多干货 公众号 程序员小明1024
* 创建时间: 2023-02-27
******************************/
@PostMapping("/del/batch")
public boolean deleteBatch(@RequestBody List<Integer> ids){
return roleService.removeByIds(ids);
}
/******************************
* 用途说明:
* 作者姓名: 更多干货 公众号 程序员小明1024
* 创建时间: 2023-02-27
******************************/
@GetMapping
public List<Role> findAll(){
return roleService.list();
}
/******************************
* 用途说明:
* 作者姓名: 更多干货 公众号 程序员小明1024
* 创建时间: 2023-02-27
******************************/
@GetMapping("/{id}")
public Role findOne(@PathVariable Integer id){
return roleService.getById(id);
}
/******************************
* 用途说明:
* 作者姓名: 更多干货 公众号 程序员小明1024
* 创建时间: 2023-02-27
******************************/
@GetMapping("/page")
public Page<Role> findPage(@RequestParam Integer pageNum,
@RequestParam Integer pageSize){
QueryWrapper<Role> queryWrapper=new QueryWrapper<>();
queryWrapper.orderByDesc("id");
return roleService.page(new Page<>(pageNum,pageSize),queryWrapper);
}
}
entity
package com.stu.study.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
/**
* <p>
*
* </p>
*
* @author 程序员小明1024
* @since 2023-02-27
*/
@Getter
@Setter
@TableName("sys_role")
@ApiModel(value = "Role对象", description = "")
public class Role implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty("id")
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@ApiModelProperty("名称")
private String name;
@ApiModelProperty("描述")
private String description;
@ApiModelProperty("唯一标识")
private String flag;
}
service接口
package com.stu.study.service;
import com.stu.study.entity.Role;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 服务类
* </p>
*
* @author 程序员小明1024
* @since 2023-02-27
*/
public interface IRoleService extends IService<Role> {
}
service实现类
package com.stu.study.service.impl;
import com.stu.study.entity.Role;
import com.stu.study.mapper.RoleMapper;
import com.stu.study.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 服务实现类
* </p>
*
* @author 程序员小明1024
* @since 2023-02-27
*/
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
}
mapper接口,因为上边的配置类,配置了加了@MapperScan("com.stu.**.mapper"),所以mapper接口可以省略@Mapper注解
package com.stu.study.mapper;
import com.stu.study.entity.Role;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author 程序员小明1024
* @since 2023-02-27
*/
//@Mapper
public interface RoleMapper extends BaseMapper<Role> {
}
mapper.xml
<?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.stu.study.mapper.RoleMapper">
</mapper>
二、改进完善版
1、新增工具类统一返回结果类R
package com.stu.myserver.utils;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.HashMap;
import java.util.Map;
/**
- 全局统一返回结果
*/
@Data
@ApiModel(value = "全局统一返回结果")
public class R {
@ApiModelProperty(value = "是否成功")
private Boolean success;
@ApiModelProperty(value = "返回码")
private Integer code;
@ApiModelProperty(value = "返回消息")
private String message;
@ApiModelProperty(value = "返回数据")
private Map<String, Object> data = new HashMap<>();
public R() {
}
public static R ok() {
R r = new R();
r.setSuccess(com.stu.myserver.utils.ResultCodeEnum.SUCCESS.getSuccess());
r.setCode(com.stu.myserver.utils.ResultCodeEnum.SUCCESS.getCode());
r.setMessage(com.stu.myserver.utils.ResultCodeEnum.SUCCESS.getMessage());
return r;
}
public static R error() {
R r = new R();
r.setSuccess(com.stu.myserver.utils.ResultCodeEnum.UNKNOWN_REASON.getSuccess());
r.setCode(com.stu.myserver.utils.ResultCodeEnum.UNKNOWN_REASON.getCode());
r.setMessage(com.stu.myserver.utils.ResultCodeEnum.UNKNOWN_REASON.getMessage());
return r;
}
public static R setResult(com.stu.myserver.utils.ResultCodeEnum resultCodeEnum) {
R r = new R();
r.setSuccess(resultCodeEnum.getSuccess());
r.setCode(resultCodeEnum.getCode());
r.setMessage(resultCodeEnum.getMessage());
return r;
}
public R success(Boolean success) {
this.setSuccess(success);
return this;
}
public R message(String message) {
this.setMessage(message);
return this;
}
public R code(Integer code) {
this.setCode(code);
return this;
}
public R data(String key, Object value) {
this.data.put(key, value);
return this;
}
public R data(Map<String, Object> map) {
this.setData(map);
return this;
}
}
2、新增枚举类ResultCodeEnum
package com.stu.myserver.utils;
import lombok.Getter;
import lombok.ToString;
/**
* 前后端数据交换状态码
*/
@Getter
@ToString
public enum ResultCodeEnum {
SUCCESS(true, 20000, "成功"),
UNKNOWN_REASON(false, 20001, "未知错误"),
UPDATE_ERROR(false, 20002, "更新失败"),
BAD_SQL_GRAMMAR(false, 21001, "sql 语法错误"),
JSON_PARSE_ERROR(false, 21002, "json 解析异常"),
PARAM_ERROR(false, 21003, "参数不正确"),
FILE_UPLOAD_ERROR(false, 21004, "文件上传错误"),
FILE_DELETE_ERROR(false, 21005, "文件刪除错误"),
EXCEL_DATA_IMPORT_ERROR(false, 21006, "Excel 数据导入错误"),
VIDEO_UPLOAD_ALIYUN_ERROR(false, 22001, "视频上传至阿里云失败"),
VIDEO_UPLOAD_TOMCAT_ERROR(false, 22002, "视频上传至业务服务器失败"),
VIDEO_DELETE_ALIYUN_ERROR(false, 22003, "阿里云视频文件删除失败"),
FETCH_VIDEO_UPLOADAUTH_ERROR(false, 22004, "获取上传地址和凭证失败"),
REFRESH_VIDEO_UPLOADAUTH_ERROR(false, 22005, "刷新上传地址和凭证失败"),
FETCH_PLAYAUTH_ERROR(false, 22006, "获取播放凭证失败"),
URL_ENCODE_ERROR(false, 23001, "URL编码失败"),
ILLEGAL_CALLBACK_REQUEST_ERROR(false, 23002, "非法回调请求"),
FETCH_ACCESSTOKEN_FAILD(false, 23003, "获取 accessToken 失败"),
FETCH_USERINFO_ERROR(false, 23004, "获取用户信息失败"),
LOGIN_ERROR(false, 23005, "登录失败"),
COMMENT_EMPTY(false, 24006, "评论内容必须填写"),
PAY_RUN(false, 25000, "支付中"),
PAY_UNIFIEDORDER_ERROR(false, 25001, "统一下单错误"),
PAY_ORDERQUERY_ERROR(false, 25002, "查询支付结果错误"),
ORDER_EXIST_ERROR(false, 25003, "课程已购买"),
GATEWAY_ERROR(false, 26000, "服务不能访问"),
CODE_ERROR(false, 28000, "验证码错误"),
LOGIN_PHONE_ERROR(false, 28009, "手机号码不正确"),
LOGIN_MOBILE_ERROR(false, 28001, "账号不正确"),
LOGIN_PASSWORD_ERROR(false, 28008, "密码不正确"),
LOGIN_DISABLED_ERROR(false, 28002, "该用户已被禁用"),
REGISTER_MOBLE_ERROR(false, 28003, "手机号已被注册"),
LOGIN_AUTH(false, 28004, "需要登录"),
LOGIN_ACL(false, 28005, "没有权限"),
SMS_SEND_ERROR(false, 28006, "短信发送失败"),
SMS_SEND_ERROR_BUSINESS_LIMIT_CONTROL(false, 28007, "短信发送过于频繁"),
DIVIDE_ZERO(false, 29001, "除零错误"),
DATA_NULL(false, 30001, "数据不存在!"),
DATA_EXITS(false, 30002, "数据已存在!"),
DATA_NODE_EXITS(false, 30003, "该章节下存在视频课程,请先删除视频课程!");
private final Boolean success;
private final Integer code;
private final String message;
ResultCodeEnum(Boolean success, Integer code, String message) {
this.success = success;
this.code = code;
this.message = message;
}
}
3、修改controller.java.vm,修改为返回统一的结果集R
注意这里把新增的统一返回结果的类和枚举类导入,位置可能不一样,导入你自己新增的文件位置
import com.stu.myserver.utils.*;
package ${package.Controller};
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.web.bind.annotation.PathVariable;
import ${package.Service}.${table.serviceName};
import ${package.Entity}.${entity};
import com.stu.myserver.utils.*;
#if(${restControllerStyle})
import org.springframework.web.bind.annotation.RestController;
#else
import org.springframework.stereotype.Controller;
#end
#if(${superControllerClassPackage})
import ${superControllerClassPackage};
#end
/**
* <p>
* $!{table.comment}
* </p>
*
* @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;
// 新增或者更新
/***********************************
* 用途说明:
* @param ${table.entityPath}
* 返回值说明:
* @return R
***********************************/
@PostMapping("add")
public R add(@RequestBody ${entity} ${table.entityPath}){
boolean result= ${table.entityPath}Service.save(${table.entityPath});
if(result){
return R.ok().message(ResultCodeEnum.SUCCESS.getMessage());
}else{
return R.error().message(ResultCodeEnum.UPDATE_ERROR.getMessage());
}
}
/***********************************
* 用途说明:
* @param id
* 返回值说明:
* @return R
***********************************/
@DeleteMapping("/{id}")
public R delete(@PathVariable Integer id){
boolean result= ${table.entityPath}Service.removeById(id);
if(result){
return R.ok().message(ResultCodeEnum.SUCCESS.getMessage());
}else{
return R.error().message(ResultCodeEnum.UPDATE_ERROR.getMessage());
}
}
/***********************************
* 用途说明:
* @param ids
* 返回值说明:
* @return R
***********************************/
@PostMapping("/del/batch")
public R deleteBatch(@RequestBody List<Integer> ids){
boolean result= ${table.entityPath}Service.removeByIds(ids);
if(result){
return R.ok().message(ResultCodeEnum.SUCCESS.getMessage());
}else{
return R.error().message(ResultCodeEnum.UPDATE_ERROR.getMessage());
}
}
/***********************************
* 用途说明:
* @param:
* 返回值说明:
* @return R
***********************************/
@GetMapping
public R findAll(){
return R.ok().data("data", ${table.entityPath}Service.list());
}
/***********************************
* 用途说明:
* @param id
* 返回值说明:
* @return R
***********************************/
@GetMapping("/{id}")
public R findOne(@PathVariable Integer id){
return R.ok().data("data", ${table.entityPath}Service.getById(id));
}
/***********************************
* 用途说明:
* @param pageNum pageSize ${table.entityPath}
* 返回值说明:
* @return R
***********************************/
@PostMapping("/page")
public R findPage(@RequestParam Integer pageNum,
@RequestParam Integer pageSize,
@RequestBody ${entity} ${table.entityPath}){
QueryWrapper<${entity}> queryWrapper=new QueryWrapper<>();
queryWrapper.orderByDesc("id");
return R.ok().data("data", ${table.entityPath}Service.page(new Page<>(pageNum,pageSize),queryWrapper));
}
}
#end