数据库准备
data_test.sql:
/* SQLyog Enterprise v12.08 (64 bit) MySQL - 5.7.31 : Database - data_test ********************************************************************* */ /*!40101 SET NAMES utf8 */; /*!40101 SET SQL_MODE=''*/; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; CREATE DATABASE /*!32312 IF NOT EXISTS*/`data_test` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `data_test`; /*Table structure for table `user` */ DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `user_id` int(11) NOT NULL AUTO_INCREMENT, `user_name` varchar(50) CHARACTER SET utf8 NOT NULL COMMENT '账号', `password` varchar(50) CHARACTER SET utf8 NOT NULL COMMENT '密码', `user_state` varchar(10) CHARACTER SET utf8 NOT NULL DEFAULT '1' COMMENT '状态,逻辑删除', PRIMARY KEY (`user_id`) ) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8; /*Data for the table `user` */ LOCK TABLES `user` WRITE; insert into `user`(`user_id`,`user_name`,`password`,`user_state`) values (1,'keafmd','keafmd','1'),(3,'21312321','123','0'),(11,'213','213','1'),(12,'keafmd','666','0'); UNLOCK TABLES; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
后端搭建
1、快速创建个SpringBoot项目
第一步:Spring Initializr
第二步:Spring Initializr Project Settings
第三步:添加个Lombok工具
第四步:Finish
初始化的样子:
2、引入依赖
此处贴上整个pom.xml,部分依赖可能对于简单需求而言是多余的,可以自行舍弃。
pom.xml代码:
<?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.4.5</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.keafmd</groupId> <artifactId>springboot-server</artifactId> <version>0.0.1-SNAPSHOT</version> <name>springboot-server</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <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.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>20.0</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.3.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.49</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.3.2</version> <scope>test</scope> </dependency> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.31</version> <scope>test</scope> </dependency> <dependency> <groupId>io.github.yedaxia</groupId> <artifactId>japidocs</artifactId> <version>1.4.3</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.6</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.73</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils --> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.9.4</version> </dependency> <!-- 解密程序 https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk15on --> <dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk15on</artifactId> <version>1.68</version> </dependency> <!--JWT 依赖 --> <dependency> <groupId>com.auth0</groupId> <artifactId>java-jwt</artifactId> <version>3.4.0</version> </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>
3、编写代码快速生成代码
因为此代码为辅助代码,放在test包下即可,相关的数据库信息以及包信息需要和你们自己的保持一致,自行修改,如何包命名和我一致,只需要修改数据库相关信息即可。
CodeGenerator:
package com.keafmd.mp; import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException; import com.baomidou.mybatisplus.core.toolkit.StringPool; import com.baomidou.mybatisplus.core.toolkit.StringUtils; 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.NamingStrategy; import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine; import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * Keafmd * * @ClassName: CodeGenerator * @Description: 代码生成器 * @author: 牛哄哄的柯南 * @Date: 2021-04-29 17:06 * @Blog: https://keafmd.blog.csdn.net/ */ public class CodeGenerator { /** * <p> * 读取控制台内容 * </p> */ public static String scanner(String tip) { Scanner scanner = new Scanner(System.in); StringBuilder help = new StringBuilder(); help.append("请输入" + tip + ":"); System.out.println(help.toString()); if (scanner.hasNext()) { String ipt = scanner.next(); if (StringUtils.isNotBlank(ipt)) { return ipt; } } throw new MybatisPlusException("请输入正确的" + tip + "!"); } public static void main(String[] args) { // 代码生成器 AutoGenerator mpg = new AutoGenerator(); // 全局配置 GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); // System.out.println("projectPath = " + projectPath); gc.setOutputDir(projectPath + "/src/main/java"); // gc.setOutputDir("D:\\test"); gc.setAuthor("关注公众号:牛哄哄的柯南"); gc.setOpen(false); // gc.setSwagger2(true); 实体属性 Swagger2 注解 gc.setServiceName("%sService"); mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://127.0.0.1:3306/data_test?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC"); // dsc.setSchemaName("public"); dsc.setDriverName("com.mysql.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("18044229"); mpg.setDataSource(dsc); // 包配置 PackageConfig pc = new PackageConfig(); pc.setModuleName(null); pc.setParent("com.keafmd"); mpg.setPackageInfo(pc); // 自定义配置 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { // to do nothing } }; // 如果模板引擎是 freemarker String templatePath = "/templates/mapper.xml.ftl"; // 如果模板引擎是 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/com/keafmd/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; } }); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); // 配置模板 TemplateConfig templateConfig = new TemplateConfig(); templateConfig.setXml(null); mpg.setTemplate(templateConfig); // 策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); strategy.setEntityLombokModel(true); strategy.setRestControllerStyle(true); strategy.setInclude(scanner("表名,多个英文逗号分割").split(",")); strategy.setControllerMappingHyphenStyle(true); strategy.setTablePrefix("m_"); mpg.setStrategy(strategy); mpg.setTemplateEngine(new FreemarkerTemplateEngine()); mpg.execute(); } }
4、运行代码生成器生成代码
在控制台输入user(表名)
红框内为自动生成的代码:
5、编写application.properties
个人习惯把application.properties改为application.yml,修改端口为80
server: port: 80 spring: datasource: url: jdbc:mysql://127.0.0.1/data_test?useSSL=false&&characterEncoding=UTF-8 driver-class-name: com.mysql.jdbc.Driver username: root password: 18044229 jackson: date-format: yyyy-MM-dd HH:mm:ss time-zone: GMT+8 mvc: throw-exception-if-no-handler-found: true web: resources: add-mappings: false
6、在启动类上添加@MapperScan
SpringbootServerApplication:
package com.keafmd; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @MapperScan("com.keafmd.mapper") public class SpringbootServerApplication { public static void main(String[] args) { SpringApplication.run(SpringbootServerApplication.class, args); } }
7、编写测试代码测试数据库是否连接正确
1、在 UserMapper代码页大括号内,按下Alt+Insert,选择Test
2、Ok
3、自动生成了测试类
4、编写测试代码
UserMapperTest :
package com.keafmd.mapper; import com.keafmd.SpringbootServerApplication; import com.keafmd.entity.User; import com.keafmd.service.UserService; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import javax.annotation.Resource; import java.util.List; import static org.junit.jupiter.api.Assertions.*; @SpringBootTest(classes = SpringbootServerApplication.class) class UserMapperTest { @Resource UserService userService; @Test public void test1(){ List<User> userList = userService.list(); for (User user : userList) { System.out.println(user); } } }
5、测试结果
至此,后端和数据库连接没问题。
8、编写后端的工具类代码(封装结果集、日期处理、解决跨域请求)
1、CommonResult
package com.keafmd.common; import lombok.Getter; /** * Keafmd * * @ClassName: CommonResult * @Description: 封装结果集 * @author: 牛哄哄的柯南 * @Date: 2021-04-29 18:11 * @Blog: https://keafmd.blog.csdn.net/ */ @Getter public class CommonResult { private Integer code; private String message; private Object obj; private CommonResult(Integer code, String message, Object obj) { this.code = code; this.message = message; this.obj = obj; } public static CommonResult nohandler() { return new CommonResult(ResultCode.NOHANDLER.getCode(), ResultCode.NOHANDLER.getMessage(),null); } public static CommonResult success(Object data) { return new CommonResult(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(),data); } public static CommonResult failed() { return new CommonResult(ResultCode.FAILED.getCode(), ResultCode.FAILED.getMessage(),null); } public static CommonResult failed(String message) { return new CommonResult(ResultCode.FAILED.getCode(),message,null); } public static CommonResult notoken() { return new CommonResult(ResultCode.NOTOKEN.getCode(), ResultCode.NOTOKEN.getMessage(),null); } public static CommonResult nopremiss() { return new CommonResult(ResultCode.NOPERMISS.getCode(), ResultCode.NOPERMISS.getMessage(),null); } }
2、DateConverter
package com.keafmd.common; import org.springframework.context.annotation.Configuration; import org.springframework.core.convert.converter.Converter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.regex.Pattern; /** * Keafmd * * @ClassName: DateConverter * @Description: 日期处理 * @author: 牛哄哄的柯南 * @Date: 2021-04-29 18:11 * @Blog: https://keafmd.blog.csdn.net/ */ @Configuration public class DateConverter implements Converter<String, Date> { public DateConverter() { // System.out.println("初始化........"); } static List<SimpleDateFormat> sdfs = new ArrayList(); static { sdfs.add(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")); sdfs.add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); sdfs.add(new SimpleDateFormat("yyyy-MM-dd")); sdfs.add(new SimpleDateFormat("yyyy/MM/dd")); } @Override public Date convert(String s) { SimpleDateFormat sdf = null; if (Pattern.matches("^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$", s)) { sdf = sdfs.get(1); } else if (Pattern.matches("^\\d{4}/\\d{2}/\\d{2} \\d{2}:\\d{2}:\\d{2}$", s)){ sdf = sdfs.get(0); } else if (Pattern.matches("^\\d{4}/\\d{2}/\\d{2}$", s)){ sdf = sdfs.get(3); } else if (Pattern.matches("^\\d{4}-\\d{2}/-\\d{2}}$", s)){ sdf = sdfs.get(2); } Date date = null; try { date = sdf.parse(s); } catch (ParseException e) { e.printStackTrace(); } return date; } }
3、LocalDateTimeConverter
package com.keafmd.common; import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; /** * Keafmd * * @ClassName: LocalDateTimeConverter * @Description: 日期处理 * @author: 牛哄哄的柯南 * @Date: 2021-04-29 18:11 * @Blog: https://keafmd.blog.csdn.net/ */ @Component public class LocalDateTimeConverter implements Converter<String, LocalDateTime> { //2021-04-29%2001:02:03 @Override public LocalDateTime convert(String s) { return LocalDateTime.parse(s, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); } }
4、ResultCode
package com.keafmd.common; import lombok.Getter; /** * Keafmd * * @ClassName: ResultCode * @Description: 结果代码 * @author: 牛哄哄的柯南 * @Date: 2021-04-29 18:11 * @Blog: https://keafmd.blog.csdn.net/ */ @Getter public enum ResultCode { NOHANDLER(404,"请求地址错误"), SUCCESS(200,"操作成功"), FAILED(500,"操作失败"), NOTOKEN(401,"未登录或登录已超时"), NOPERMISS(403,"无操作权限"), ; private Integer code; private String message; ResultCode(Integer code, String message) { this.code = code; this.message = message; } }
5、AppConfig
package com.keafmd.config; import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; import com.baomidou.mybatisplus.extension.plugins.pagination.dialects.MySqlDialect; import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; import com.keafmd.common.DateConverter; import com.keafmd.common.LocalDateTimeConverter; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.format.FormatterRegistry; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.List; /** * Keafmd * * @ClassName: AppConfig * @Description: 解决跨域请求 * @author: 牛哄哄的柯南 * @Date: 2021-04-29 18:11 * @Blog: https://keafmd.blog.csdn.net/ */ @Configuration public class AppConfig extends WebMvcConfigurationSupport { /** * 分页插件 * @return */ @Bean public PaginationInterceptor paginationInterceptor() { PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); paginationInterceptor.setDialect(new MySqlDialect()); paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true)); return paginationInterceptor; } @Bean FilterRegistrationBean<CorsFilter> cors(){ FilterRegistrationBean<CorsFilter> registrationBean = new FilterRegistrationBean<CorsFilter>(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin("http://127.0.0.1:81"); config.addAllowedHeader("*"); config.addAllowedMethod("*"); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); CorsFilter filter = new CorsFilter(source); registrationBean.setFilter(filter); registrationBean.addUrlPatterns("/*"); return registrationBean; } /** * curl http://127.0.0.1/user/getById?id=31 * @param converters */ @Override protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE); // objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); //忽略 null 字段 JavaTimeModule javaTimeModule = new JavaTimeModule(); javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd"))); // javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); // javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd"))); objectMapper.registerModule(javaTimeModule); converters.add(new MappingJackson2HttpMessageConverter(objectMapper)); } @Override protected void addFormatters(FormatterRegistry registry) { super.addFormatters(registry); registry.addConverter(new DateConverter()); registry.addConverter(new LocalDateTimeConverter()); } }
6、DefaultExceptionHandler
package com.keafmd.config; import com.keafmd.common.CommonResult; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.servlet.NoHandlerFoundException; import javax.servlet.http.HttpServletRequest; /** * Keafmd * * @ClassName: DefaultExceptionHandler * @Description: * @author: 牛哄哄的柯南 * @Date: 2021-04-29 18:11 * @Blog: https://keafmd.blog.csdn.net/ */ @RestControllerAdvice public class DefaultExceptionHandler { @ExceptionHandler public CommonResult exceptionHandler(HttpServletRequest request, Exception ex) { ex.printStackTrace(); if(ex instanceof NoHandlerFoundException) { return CommonResult.nohandler(); } return CommonResult.failed(ex.getMessage()); } }
9、编写后端的增删改查代码
1、在UserService接口中编写分页查询代码
package com.keafmd.service; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.keafmd.entity.User; import com.baomidou.mybatisplus.extension.service.IService; /** * <p> * 服务类 * </p> * * @author 关注公众号:牛哄哄的柯南 * @since 2021-04-29 */ public interface UserService extends IService<User> { Page pageList(Page page, User user); }
2、在UserServiceImpl实现类中实现分页查询和模糊查找
package com.keafmd.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.toolkit.StringUtils; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.keafmd.entity.User; import com.keafmd.mapper.UserMapper; import com.keafmd.service.UserService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** * <p> * 服务实现类 * </p> * * @author 关注公众号:牛哄哄的柯南 * @since 2021-04-29 */ @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { @Override public Page pageList(Page page, User user) { if(page == null){ page = new Page(); } QueryWrapper wrapper = new QueryWrapper(); if(user!=null && StringUtils.isNotEmpty(user.getUserName())){ //根据user_name字段模糊查找 wrapper.like("user_name",user.getUserName()); } return super.page(page,wrapper); } }
3、在UserController中编写增删改查代码
package com.keafmd.controller; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.keafmd.common.CommonResult; import com.keafmd.entity.User; import com.keafmd.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Arrays; /** * <p> * 前端控制器 * </p> * * @author 关注公众号:牛哄哄的柯南 * @since 2021-04-29 */ @RestController @RequestMapping("/user") public class UserController { @Autowired UserService userService; /** * 查找 * @return */ @RequestMapping("/list") CommonResult list(ModelMap modelMap, Page page, @ModelAttribute("user") User user) { page = userService.pageList(page, user); modelMap.addAttribute("page", page); return CommonResult.success(page); } @RequestMapping("/save") CommonResult save(User user){ return CommonResult.success(userService.saveOrUpdate(user)); } /** * 根据id查 * @param id * @return */ @RequestMapping("/getById") CommonResult getById(Integer id) { return CommonResult.success(userService.getById(id)); } /** * 删除,逻辑删除 * @param id * @return */ @RequestMapping("/del") CommonResult del(Integer id ) { User user = userService.getById(id); user.setUserState("0"); return CommonResult.success(userService.updateById(user)); } /** * 批量删除 * @param id * @return */ @RequestMapping("/delByIds") CommonResult delByIds(Integer[] id) { /*for (Integer integer : id) { System.out.println(integer); }*/ return CommonResult.success(userService.removeByIds(Arrays.asList(id))); } }
前端搭建
由于篇幅有限,前端搭建单独再写一篇
SpringBoot+MyBatisPlus+Vue 前后端分离项目快速搭建【前端篇】【快速生成后端代码、封装结果集、增删改查、模糊查找】【毕设基础框架】
以上就是SpringBoot+MyBatisPlus+Vue 前后端分离项目快速搭建【后端篇】【快速生成后端代码、封装结果集、增删改查、模糊查找】【毕设基础框架】的全部内容