目录
2.3.修改application.properties配置文件
2.4.创建代码生成器MybatisPlusGenerator.java
4.1.运行代码生成器MybatisPlusGenerator.java
4.1.TbZoneController.java中编写CRUD
1.创建springboot项目
...
2.环境准备
2.1.数据库
DROP TABLE IF EXISTS `tb_zone`; CREATE TABLE `tb_zone` ( `id` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '主键', `gmt_create` datetime(0) NOT NULL COMMENT '创建时间', `gmt_modified` datetime(0) NULL DEFAULT NULL COMMENT '修改时间', `is_deleted` int(10) NOT NULL COMMENT '逻辑删除(0:正常;1:删除)', `is_disable` int(11) NOT NULL COMMENT '状态(0:正常;1:禁用)', `zone_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '名称', `zone_desc` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '描述', PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '专区' ROW_FORMAT = Compact; -- ---------------------------- -- Records of tb_zone -- ---------------------------- INSERT INTO `tb_zone` VALUES ('1', '2022-09-02 10:00:34', '2022-09-22 13:52:11', 0, 0, '农副产品', '瓜果蔬菜 无公害 无污染'); INSERT INTO `tb_zone` VALUES ('2', '2018-07-04 10:45:07', '2022-09-02 09:18:39', 0, 0, '海鲜水产', '龙虾 螃蟹 生蚝 种类齐全'); INSERT INTO `tb_zone` VALUES ('3', '2018-07-04 10:45:07', '2022-09-02 11:13:36', 0, 0, '香甜水果', '葡梨浆果 多汁鲜物'); INSERT INTO `tb_zone` VALUES ('4', '2018-07-04 10:45:07', '2021-06-21 10:58:07', 0, 0, '有机蔬菜', '无公害 脆嫩 新鲜润胃'); INSERT INTO `tb_zone` VALUES ('5', '2018-07-04 10:45:07', '2021-06-21 10:58:07', 0, 0, '粮油专区', ' 非转基因 调和油 植物油');
2.2.引入依赖
<?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.12.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>CS1</artifactId> <version>0.0.1-SNAPSHOT</version> <name>CS1</name> <description>CS1</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <!--引入mp--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.1</version> </dependency> <!--mp代码生成器的依赖--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.5.1</version> </dependency> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.3</version> </dependency> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.29</version> </dependency> <!--swagger的依赖引入--> <dependency> <groupId>io.github.jianzhichun</groupId> <artifactId>spring-boot-starter-swagger2</artifactId> <version>0.0.1</version> </dependency> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>swagger-bootstrap-ui</artifactId> <version>1.9.6</version> </dependency> <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>2.3.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> <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-test</artifactId> <version>2.3.1</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <excludes> <exclude> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </exclude> </excludes> </configuration> </plugin> </plugins> </build> </project>
2.3.修改application.properties配置文件
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/mybatisplus?serverTimezone=Asia/Shanghai&characterEncoding=UTF8 spring.datasource.username=root spring.datasource.password=123456789 mybatis-plus.mapper-locations=classpath:/mapper/*.xml mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
2.4.创建代码生成器MybatisPlusGenerator.java
package com.wqg; import com.baomidou.mybatisplus.generator.FastAutoGenerator; import com.baomidou.mybatisplus.generator.config.OutputFile; import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; import java.util.Collections; public class MybatisPlusGenerator { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/mybatisplus?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai"; String projectPath = "D:\\java1\\reggie\\CS1"; FastAutoGenerator.create(url, "root", "123456789") .globalConfig(builder -> { builder.author("WQG") // 设置作者 .enableSwagger() // 开启 swagger 模式 .fileOverride() // 覆盖已生成文件 .outputDir(projectPath + "/src/main/java"); // 指定输出目录 }) .packageConfig(builder -> { builder.parent("com.wqg") // 设置父包名 .moduleName("zone") // 设置父包模块名 .pathInfo(Collections.singletonMap(OutputFile.mapperXml, projectPath + "/src/main/resources/mapper/"));// 设置mapperXml生成路径 }) .strategyConfig(builder -> { builder.entityBuilder().enableLombok();//启用lombok builder.mapperBuilder().enableMapperAnnotation().build();//启用映射器注释 builder.controllerBuilder().enableHyphenStyle() // 开启驼峰转连字符 .enableRestStyle(); // 开启生成@RestController 控制器 builder.addInclude("tb_zone"); // 设置需要生成的表名 }) .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板 // 开始处理 .execute(); } }
2.5.创建SwaggerConfig.java配置文件
package com.wqg.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; @Configuration //表示类似与配置文件 public class SwaggerConfig { @Bean //加在方法上,表示吧方法的返回结果交于spring容器来管理该对象. 里面封装了接口文档的信息, public Docket docket(){ Docket docket=new Docket(DocumentationType.SWAGGER_2) .groupName("qy165") .apiInfo(getInfo()) .select() //只为com.aaa.controller包下的类生成接口文档 .apis(RequestHandlerSelectors.basePackage("com.wqg")) .build(); return docket; } private ApiInfo getInfo(){ Contact DEFAULT_CONTACT = new Contact("张三", "http://www.jd.com", "110@qq.com"); ApiInfo apiInfo= new ApiInfo("员工管理系统API文档", "员工管理系统API文档", "1.5", "localhost:8081/doc.html", DEFAULT_CONTACT, "AAA志远网络有限公司", "http://www.aaa.com"); return apiInfo; } }
2.6.创建分页配置类
@Configuration public class MybatisPlusConfig { //分页配置类 /** * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除) */ @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return interceptor; } }
2.7.创建类:统一响应的json数据
@NoArgsConstructor @AllArgsConstructor @Data @ApiModel(value = "统一响应的json数据") public class Result { //表示状态码 @ApiModelProperty(value = "状态码 200表示成功 500表示服务器错误 401表示权限不足") private Integer code; //消息提示 @ApiModelProperty(value = "响应的消息内容") private String msg; //响应的数据内容 @ApiModelProperty(value = "响应的数据") private Object data; }
2.8.条件查询中所需要的条件
@Data @NoArgsConstructor @AllArgsConstructor @ApiModel(value = "条件查询") public class ZoneVo { @ApiModelProperty("状态(0:正常;1:禁用)") private Integer isDisable; @ApiModelProperty("名称") private String zoneName; }
3.前端准备
3.1.引入前端所需要的 js,css文件(在代码包中)
3.2.前端页面布局及CRUD
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>产品管理</title> <script type="text/javascript" src="/js/vue.js"></script> <script type="text/javascript" src="/js/index.js"></script> <script type="text/javascript" src="/js/axios.min.js"></script> <link type="text/css" rel="stylesheet" href="/css/index.css"/> </head> <body> <div id="app"> <!--搜索表单--> <el-form :inline="true" :model="userVo" class="demo-form-inline"> <el-form-item label="专区名称:"> <el-input v-model="userVo.zoneName" placeholder="专区名称"></el-input> </el-form-item> <el-form-item label="状态"> <el-select v-model="userVo.isDisable" placeholder="状态"> <el-option label="正常" value="0"></el-option> <el-option label="禁用" value="1"></el-option> </el-select> </el-form-item> <el-form-item> <el-button type="primary" @click="searchUser">查询</el-button> <el-button type="warning" icon="el-icon-refresh" @click="resetUserVo"></el-button> <!--添加--> <el-button type="success" @click="addUser">添加</el-button> </el-form-item> </el-form> <!--修改--> <el-dialog title="修改产品" :visible.sync="editDialogVisible" width="30%"> <el-form ref="form" :model="editUserForm" label-width="80px"> <el-form-item label="专区名称"> <el-input v-model="editUserForm.zoneName"></el-input> </el-form-item> <el-form-item label="专区描述"> <el-input v-model="editUserForm.zoneDesc"></el-input> </el-form-item> <el-form-item label="状态" prop="isDisable"> <el-tooltip :content="'0为正常,1为禁用' + editUserForm.isDisable" placement="top"> <el-switch v-model="editUserForm.isDisable" active-color="#13ce66" inactive-color="#ff4949" :active-value="0" :inactive-value="1" active-text="正常" inactive-text="禁用"> </el-switch> </el-tooltip> </el-form-item> </el-form> <span slot="footer" class="dialog-footer"> <el-button @click="editDialogVisible = false">取 消</el-button> <el-button type="primary" @click="confirmUpdateUser">确 定</el-button> </span> </el-dialog> <!--添加--> <el-dialog title="添加信息" :visible.sync="dialogVisible" width="30%"> <el-form ref="form" :model="addUserForm" label-width="80px"> <el-form-item label="专区名称"> <el-input v-model="addUserForm.zoneName"></el-input> </el-form-item> <el-form-item label="专区描述"> <el-input v-model="addUserForm.zoneDesc"></el-input> </el-form-item> <el-form-item label="状态" prop="isDisable"> <el-tooltip :content="'0为正常,1为禁用' + addUserForm.isDisable" placement="top"> <el-switch v-model="addUserForm.isDisable" active-color="#13ce66" inactive-color="#ff4949" :active-value="0" :inactive-value="1" active-text="正常" inactive-text="禁用"> </el-switch> </el-tooltip> </el-form-item> <el-form-item label="逻辑删除" prop="isDisable"> <el-radio v-model="addUserForm.isDeleted" label="0">正常</el-radio> <el-radio v-model="addUserForm.isDeleted" label="1">删除</el-radio> </el-form-item> </el-form> <span slot="footer" class="dialog-footer"> <el-button @click="dialogVisible = false">取 消</el-button> <el-button type="primary" @click="confirmAddUser">确 定</el-button> </span> </el-dialog> <!--布局--> <el-table :data="userList" border style="width: 100%"> <el-table-column prop="id" label="序号" width="80"> </el-table-column> <el-table-column prop="zoneName" label="专区名称"> </el-table-column> <el-table-column prop="zoneDesc" label="专区描述"> </el-table-column> <el-table-column prop="gmtCreate" label="添加时间"> </el-table-column> <el-table-column prop="isDisable" label="状态"> <template slot-scope="scope"> <el-switch style="display: block" v-model="scope.row.isDisable" active-color="#13ce66" inactive-color="#ff4949" :active-value="0" :inactive-value="1" active-text="正常" inactive-text="禁用" @change="changeStatus(scope.row.id,scope.row.isDisable)" > </el-switch> </template> </el-table-column> <el-table-column label="操作"> <template slot-scope="scope"> <el-button type="primary" @click="editUser(scope.row)">修改</el-button> <el-button type="danger" @click="deleteUser(scope.row.id)">删除</el-button> </template> </el-table-column> </el-table> <!--分页--> <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="current" :page-sizes="[2,4,6,10]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination> </div> </body> <script> var app = new Vue({ el: "#app", data: { //条件对象 userVo: {}, //当前页 current: 1, //当前显示条数 pageSize: 2, //总页数 total: 0, //控制修改对话的显示和隐藏 editDialogVisible: false, //修改的表单 editUserForm: {}, //控制添加对话的显示和隐藏 dialogVisible: false, //添加的表单对象 addUserForm: {}, //接收所有用户信息 userList: [], }, created() { this.userInquire(); }, methods: { //根据id修改状态 changeStatus(id, isDisable) { axios.post("/zone/tb-zone/updateIsDisable?id=" + id + "&isDisable=" + isDisable).then(result => { this.$message.success(result.data.msg); }) }, //确认修改 confirmUpdateUser() { axios.post("/zone/tb-zone/update", this.editUserForm).then(result => { this.$message.success(result.data.msg); this.editDialogVisible = false; this.userInquire(); }) }, //修改 editUser(row) { this.editDialogVisible = true; this.editUserForm = row; }, //确认添加 confirmAddUser() { axios.post("/zone/tb-zone/add", this.addUserForm).then(result => { this.$message.success(result.data.msg); this.addUserForm = {}; this.dialogVisible = false; this.userInquire(); }) }, //添加-表单显示 addUser() { this.dialogVisible = true; }, //删除 deleteUser(id) { axios.get("/zone/tb-zone/deleteById?id=" + id).then(result => { this.$message.success(result.data.msg); this.userInquire(); }) }, //查询重置 resetUserVo() { this.userVo = {}; this.userInquire(); }, //条件查询 searchUser() { this.current = 1; //点击条件查询时页码从第一页开始查询 this.userInquire(); }, handleSizeChange(val) { this.pageSize = val; this.userInquire(); }, handleCurrentChange(val) { this.current = val; this.userInquire(); }, //分页条件查询 userInquire() { axios.post("/zone/tb-zone/list?current=" + this.current + "&pageSize=" + this.pageSize, this.userVo).then(result => { this.userList = result.data.data.records; this.total = result.data.data.total; }) }, } }) </script> </html>
4.后台代码书写
4.1.运行代码生成器MybatisPlusGenerator.java
一键生成
4.1.TbZoneController.java中编写CRUD
package com.wqg.zone.controller; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.wqg.zone.entity.TbZone; import com.wqg.zone.service.ITbZoneService; import com.wqg.zone.vo.Result; import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; /** * <p> * 专区 前端控制器 * </p> * * @author WQG * @since 2023-06-25 */ @RestController @RequestMapping("/zone/tb-zone") public class TbZoneController { @Autowired private ITbZoneService tbZoneService; @ApiModelProperty @ApiOperation(value = "分页条件查询") @PostMapping("list") public Result list2(Integer current , Integer pageSize , @RequestBody TbZone tbZone){ //分页 IPage<TbZone> page = new Page<>(current,pageSize); //查询条件构造器 QueryWrapper<TbZone> wrapper = new QueryWrapper<>(); if (StringUtils.hasText(tbZone.getZoneName())){ wrapper.like("zone_name",tbZone.getZoneName()); } if (tbZone.getIsDisable() != null){ wrapper.eq("is_disable",tbZone.getIsDisable()); } IPage<TbZone> userIPage = tbZoneService.page(page,wrapper); return new Result(200,"查询成功",userIPage); } //删除 @ApiModelProperty @ApiOperation(value = "删除") @GetMapping("deleteById") public Result deleteById(String id){ boolean i = tbZoneService.removeById(id); return i == true ? new Result(200, "删除成功", null) : new Result(500, "删除失败", null); } //添加 @ApiModelProperty @ApiOperation(value = "添加") @PostMapping("add") public Result add(@RequestBody TbZone tbZone){ boolean save = tbZoneService.save(tbZone); return save == true ? new Result(200, "添加成功", null) : new Result(500, "添加失败", null); } //修改 @ApiModelProperty @ApiOperation(value = "修改") @PostMapping("update") public Result update(@RequestBody TbZone tbZone){ boolean b = tbZoneService.updateById(tbZone); return b == true ? new Result(200, "修改成功", null) : new Result(500, "修改失败", null); } //根据id修改状态 @ApiModelProperty @ApiOperation(value = "根据id修改状态") @PostMapping("updateIsDisable") public Result updateIsDisable(String id , Integer isDisable){ UpdateWrapper<TbZone> wrapper = new UpdateWrapper<>(); wrapper.eq("id",id); wrapper.set("is_disable",isDisable); boolean update = tbZoneService.update(wrapper); return update == true ? new Result(200, "状态修改成功", null) : new Result(500, "状态修改失败", null); } }
5.项目总览
5.1.包
5.2.最终效果图
SpringBoot+MybatisPlus完成单表CRUD
于 2023-06-25 19:41:21 首次发布