Bootstrap

非常简单实用的前后端分离项目-仓库管理系统(Springboot+Vue)part 1

非常简单实用的前后端分离项目-仓库管理系统(Springboot+Vue)_哔哩哔哩_bilibili

一、创建后端项目

1. 创建文件夹spring_vue_wms
2. 打开这个文件夹
3. 右键点击创建新模块(springboot)
右键打开new module,选择spring initializr


Develop tools选择Lombok,web选择spring web,sql选择mysql。创建spring的时候记得把groud那啥改成Maven,为什么我没有wms.iml文件,删除4个文件gitgnore,help.md,mvnw,mvnw.cmd

右边一栏如果没有maven,就ctrl+shift+a,选择“添加为maven项目”

,pom.xml第三十八行修改

<dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <version>5.7.42</version>
            <scope>runtime</scope>
</dependency>

第八行根据自己原作者是2.7.1到2.6.7,本次本人不与修改,认为还是3.3.5,加载泡沫文件的莫名其妙的error

<version>2.6.7</version>

总之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>3.3.5</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.wms</groupId>
	<artifactId>wms</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>wms</name>
	<description>wms</description>
	<url/>
	<licenses>
		<license/>
	</licenses>
	<developers>
		<developer/>
	</developers>
	<scm>
		<connection/>
		<developerConnection/>
		<tag/>
		<url/>
	</scm>
	<properties>
		<java.version>23</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>com.mysql</groupId>
			<artifactId>mysql-connector-j</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>
			<version>3.3.5</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>

 项目目录如下

 4. 创建测试类并测试,在wms/src/java/com.wms添加软件包controller,新建一个HelloController.java 类

package com.wms.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @GetMapping
    public String hello(){
        return "Hello World";//选择查询项via
    }
}

无效的发行版本启动失败:点右上角的设置-项目设置-选择1.8、sdk默认值,左上角打开配置搜Java Compiler选择项目编辑器版本8

运行成功!!!打开local8080可以看见网页里面hello的话

可以详细看一看视频作者的部分帮助 我也做了CSDN创作中心

友情提示:学习此项目可能需要一点点功底

二、加入mybatis—plus支持

MyBatis-Plus 🚀 为简化开发而生

1. 在xml中加入依赖代码

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId> 
    <version>3.4.1</version>
</dependency>

最新版已经达到了3.5.9 版本,右边的maven中点击刷新等待5s即可

2.创建数据库实例、创建用户表、插入默认数据

create table user
(
    id        int auto_increment comment'主键' 
        primary key,
    no        varchar(20)            null comment'账号', 
    name      varchar(100)           not null comment'名字',
    password  varchar(20)            not null comment'密码',
    age       int                    null,
    sex       int                    null comment '性别',
    phone     varchar(20)            null comment '电话', 
    role_id   int                    null comment '角色 0超级管理员,1管理员,2普通账号',
    isvalid   varchar(4) default 'Y' null comment '是否有效,Y有效,其他无效'
)

    charset utf8; 

鼠标右键点击mysql,新建数据库,

wms02 出现一个新建查询,将上述代码复制其中,点击运行


左栏选择表,出现user  

idnonamepasswordagesexphonerole_idisvalid
1sa超级管理员1231811145140Y

点击下方的小对号保存,可以刷新一下 

回到idea,resources中自动配置application.properties,改为yml文件 ( 其实不改也无所谓

 3.yml文件的配置
端口和数据源的配置,根据自己的mysql改端口号(我的就这3306-- 13306
下方第七行URL缩进很重要 url等配置应缩进在datasource下,否则会报错  ; mysql8的话在jdbc前加cj.


server:
  port:8090

spring:
  datasource:
    url: jdbc:mysql://localhost:13306/wms02?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: root

 并且idea与mysql连接,有人说写成com.mysql.cj.jdbc.Driver   error的

接下来新建多个文件

 User.java

package com.wms.entity;

import com.baomidou.mybatisplus.annotation.TableField;
import lombok. Data;

@Data
public class User {
    private int id;
    private String no;
    private String name;
    private String password;
    private int sex;
    private int roleId;
    private String phone;
    @TableField("isvalid")
    private String isValid;
}

UserMapper.java

package com.wms.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.wms. entity.User;
import org.apache.ibatis.annotations. Mapper;

@Mapper
public interface UserMapper extends BaseMapper<User> {}

 UserService.java

package com.wms.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.wms.entity.User;

public interface UserService extends IService<User>{}

 UserServiceImpl.java

package com.wms.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wms.entity.User;
import com.wms.mapper.UserMapper;
import com.wms.service.UserService;
import org. springframework. stereotype. Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

}

service类定义接口,serviceImpl对接口函数进行实现

在hellocontroller.java中暂且修改用一下list

package com.wms.controller;

import com.wms.entity.User;
import com.wms.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class HelloController {
    @GetMapping
    public String hello() {
        return "hello wms";
    }

    @Autowired
    private UserService userService;

    @GetMapping("/list")
    public List<User> list() {
        return  userService.list();
    }
}

idea是2024.1,问题在于mabayis.plus的依赖要改mybatis-plus-spring-boot3-starter,版本改成3.5.7。视频里的boot改成了spring-boot3,修改你的pom.xml并且刷新

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-spring-boot3-starter</artifactId>
    <version>3.5.7</version>
</dependency>

成功运行!!!尽管报告有错误

 根据你提供的日志信息,应用程序已经成功启动,并且Tomcat服务器正在8080端口上运行。你看到的“红色报告”可能是指日志中的警告信息。这些警告信息通常不会阻止应用程序启动,但它们指出了一些可能的问题或最佳实践。

以下是你日志中的两个警告:

1. **MySQL驱动类加载警告**:

   Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.

 这个警告是因为你的配置中可能还在使用旧的MySQL驱动类`com.mysql.jdbc.Driver`,而推荐使用的是新的驱动类`com.mysql.cj.jdbc.Driver`。这个警告告诉你,旧的驱动类已经被弃用,而且通常情况下,不需要手动加载驱动类,因为JDBC驱动会通过SPI(Service Provider Interface)机制自动被注册。

   要解决这个问题,你可以更新你的数据库连接配置,使用新的驱动类。如果你使用的是`application.properties`或`application.yml`文件,确保你的配置如下所示:


server:
  port: 8090

spring:
  datasource:
    url: jdbc:mysql://localhost:13306/wms02?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: root

2. **主键类型警告**:
   This primary key of "id" is primitive !不建议如此请使用包装类 in Class: "com.wms.entity.User"
   这个警告是MyBatis Plus发出的,它建议你的主键类型应该使用包装类(如`Integer`、`Long`等),而不是原始类型(如`int`、`long`等)。这是因为在某些情况下,原始类型可能会引起问题,比如当主键为0或负数时。

   要解决这个问题,你需要检查你的`User`实体类,并确保`id`字段使用的是包装类,例如:

   public class User {
       private Integer id; // 使用Integer而不是int
       // 其他字段和方法
   }

继续构建其他方法如add等,
HelloController.java

package com.wms.controller;

import com.wms.entity.User;
import com.wms.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class HelloController {
    @GetMapping
    public String hello() {
        return "hello wms";
    }

    @Autowired
    private UserService userService;

    @GetMapping("/list")
    public List<User> list() {
        //return  userService.list();
        return userService.listAll();
    }
}

UserServiceImpl.java

package com.wms.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wms.entity.User;
import com.wms.mapper.UserMapper;
import com.wms.service.UserService;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    private UserMapper userMapper;
    @Override
    public List<User> listAll(){
        return  userMapper.listAll();
    }
}


UserMapper.java

package com.wms. mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.wms. entity.User;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface UserMapper extends BaseMapper<User> {
    List<User> listAll();
}

UserService.java

package com.wms.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.wms.entity.User;

import java.util.List;

public interface UserService extends IService<User>{
    List<User> listAll();
}

mybatis---plus原来不支持这个,需要你来添加配置xml

我们在resource中新建文件夹mapper,新建文件UserMapper.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.wms.mapper.UserMapper">
    <select id="listAll" resultType="com.wms.entity.User">
        select * from  user
    </select>
</mapper>

可以运行 并在8090中显示

三、使用代码生成器生成代码

可以直接下载插件,在配置的时候直接勾选那个配置,会帮你下好的

<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>com.spring4all</groupId>
    <artifactId>spring-boot-starter-swagger</artifactId> 
    <version>1.5.1.RELEASE</version>
</dependency> 

先在pom.xml中添加依赖并刷新maven

在com.wms下新建软件包common,下属CodeGenerartor.java

package com.wms.common;
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;
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 + "!");
    }
    /**
     *
     操作步骤:
     *  1.修改数据源包括地址密码信息,对应代码标记:⼀、 下同
     *  2.模块配置,可以修改包名
     *  3.修改模板(这步可忽略)
     *  @param args
     */
    public static void main(String[] args) {
        //代码⽣成器
        AutoGenerator mpg = new AutoGenerator();
        //全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir")+"/wms";//地址
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("wms");//作者
        gc.setOpen(false);
        gc.setSwagger2(true); //实体属性 Swagger2 注解
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(true);// XML columList
        //去掉service接⼝⾸字⺟的I, 如DO为User则叫UserService
        gc.setServiceName("%sService");
        mpg.setGlobalConfig(gc);
        //数据源配置⼀、修改数据源
        DataSourceConfig dsc = new DataSourceConfig();
        //
        dsc.setUrl("jdbc:mysql://localhost:13306/wms02?useUnicode=true&characterEncoding=UTF8&useSSL=false");
                // dsc.setSchemaName("public");
                dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("root");
        mpg.setDataSource(dsc);
        //包配置
        PackageConfig pc = new PackageConfig();
        //pc.setModuleName(scanner("模块名"));
        // ⼆、模块配置
        pc.setParent("com.wms")
                .setEntity("entity")
                .setMapper("mapper")
                .setService("service")
                .setServiceImpl("service.impl")
                .setController("controller");
        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/mapper/" + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" +
                        StringPool.DOT_XML;
            }
        });
        /*
        cfg.setFileCreate(new IFileCreate() {
            @Override
            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType,
String filePath) {
                // 判断⾃定义⽂件夹是否需要创建
                checkDir("调⽤默认⽅法创建的⽬录,⾃定义⽬录⽤");
                if (fileType == FileType.MAPPER) {
                    // 已经⽣成 mapper ⽂件判断存在,不想重新⽣成返回 false
                    return !new File(filePath).exists();
                }
                // 允许⽣成模板⽂件
                return true;
            }
        });
        */
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        //配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        //三、修改模板
        //配置⾃定义输出模板
        //指定⾃定义模板路径,注意不要带上.ftl/.vm, 会根据使⽤的模板引擎⾃动识别
        //
        /*templateConfig.setEntity("templates/entity2.java");
        templateConfig.setService("templates/service2.java");
        templateConfig.setController("templates/controller2.java");
        templateConfig.setMapper("templates/mapper2.java");
        templateConfig.setServiceImpl("templates/serviceimpl2.java");*/

        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);
        //策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        // strategy.setSuperEntityClass("你⾃⼰的⽗类实体,没有就不⽤设置!");
        //strategy.setSuperEntityClass("BaseEntity");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        //公共⽗类
        //strategy.setSuperControllerClass("BaseController");
        // strategy.setSuperControllerClass("你⾃⼰的⽗类控制器,没有就不⽤设置!");
        //写于⽗类中的公共字段
        // strategy.setSuperEntityColumns("id");
        strategy.setInclude(scanner("表名,多个英⽂逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        //strategy.setTablePrefix(pc.getModuleName() + "_");
        //忽略表前缀tb_,⽐如说tb_user,直接映射成user对象
        //四、注意是否要去掉表前缀
        //strategy.setTablePrefix("tb_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}

试试能不能用,把helloController,实体entity的User,mapper里的UserMapper , UserServiceImpl,userservice,resource的usermapper.xml删除

右键运行Codegenerator.java

 usercontroller.java补充如下

package com.wms.controller;


import com.wms.entity.User;
import com.wms.service.UserService;
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 wms
 * @since 2024-11-19
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    
    @GetMapping
    public List<User> list(){
        return userService.list();
    }
}

由于版本问题,(时间的割裂感)pom.xml中统一用mybatis3.5.7版本,如果CodeGenerator中有部分包导不入,右键选择其他版本(如3.4.1)即可。记得通过修改pom.xml下载对应版本的依赖;

没有@Mapper的要自己在UserMapper中添加

pom.xml的部分添加

<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
			<version>3.5.7</version>
		</dependency>
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-generator</artifactId>
			<version>3.5.7</version>
		</dependency>
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-extension</artifactId>
			<version>3.5.7</version>
		</dependency>
		<dependency>
			<groupId>org.freemarker</groupId>
			<artifactId>freemarker</artifactId>
			<version>2.3.30</version>
		</dependency>
		<dependency>
			<groupId>com.spring4all</groupId>
			<artifactId>spring-boot-starter-swagger</artifactId>
			<version>1.5.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>com.baomidou</groupId>
			<artifactId>mybatis-plus-generator</artifactId>
			<version>3.4.1</version>
		</dependency>

 四、实现增删改查

Usercontroller添加增删改的功能

package com.wms.controller;


import com.wms.entity.User;
import com.wms.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wms
 * @since 2024-11-19
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/list")
    public List<User> list(){
        return userService.list();
    }

    //新增
    @PostMapping("/save")
    public boolean save(@RequestBody User user){
        return userService.save(user);
    }
    //修改
    @PostMapping("/mod")
    public boolean mod(@RequestBody User user){
        return userService.updateById(user);
    }
    //新增或修改
    @PostMapping("/saveOrMod")
    public boolean saveOrMod(@RequestBody User user){
        return userService.saveOrUpdate(user);
    }
    //删除
    @GetMapping("/delete")
    public boolean delete(Integer id){
        return userService.removeById(id);
    }


}

启动后打开postman按照如下所示输入POST的数据并且send他,200OK和true就是发送成功

 打开Navicat查询(由于本人按了两次send,因此有重复数据,不过这也反映出数据重复的处理问题

 继续更换其他方法如mod修改,修改成功!!

 以此类推,都是这样了,saveormod是修改或添加,根据数据的id存在不存在,当我i不post那个id时,就会新建了

 delete则是使用GET方法,直接导入对应的id即可实现删除

 接下来做查询。依旧是UserController中添加

//查询(模糊、匹配)
    @PostMapping("/listP")
    public List<User>listP(@RequestBody User user) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.like(User::getName, user.getName());
        return userService.list(lambdaQueryWrapper);
    }

 lambdaQueryWrapper.eq(User::getName, user.getName());
        //eq就是完全匹配

五、分页的处理

入参的封装,依旧是usercontroller测试打印是否能够成功运行
第一个参数要传入函数式接口,这写法是Lamda表达式;pagehelper的分页挺不错,mybatis-plus提供的分页插件在3.5.9版本后大更新,you can try这可以减轻很多代码量

@PostMapping("/listPage")
    public List<User>listPage(@RequestBody HashMap map){
        System.out.println(map);
        /*LambdaQueryWrapper<User>LambdaQueryWrapper=newLambdaQueryWrapper();
        LambdaQueryWrapper.eq(User::getName,user.getName());
        return userService.list(LambdaQueryWrapper);*/
 
        return null;
    }

在com.wms.common下新建方法QueryPageParam.java

package com.wms.common;
import lombok.Data;

@Data
public class QueryPageParam{
    //默认
    private static int PAGE_SIZE=20;
    private static int PAGE_NUM=1;
    private int pageSize=PAGE_SIZE;
    private int pageNum=PAGE_NUM;

}

 修改listPage

 @PostMapping("/listPage")
    public List<User>listPage(@RequestBody QueryPageParam param){
        System.out.println(param);
        //System.out.println("num==="+(String)map.get("pageSize"));

        System.out.println("num==="+param.getPageNum());
        System.out.println("size==="+param.getPageSize());
        /*LambdaQueryWrapper<User>LambdaQueryWrapper=newLambdaQueryWrapper();
        LambdaQueryWrapper.eq(User::getName,user.getName());
        return userService.list(LambdaQueryWrapper);*/

        return null;
    }

由于默认设立是20和1,自然会在idea和postman中出现如下界面

这两个参数,最后会当作sql的两个查询条件去处理分页。 

前辈说:千万不要拿Map当传参,维护火葬场  一定要用map,但是写接口文档不就行了,并且有时候参数名称是不固定的谁要是再敢用Map传参,我过去就是一JIO_idea map传参要具体类型-CSDN博客

因为原来的那种还得执行完还得强转化整型,判断是否为0什么的,所以要入参的封装

 querypage添加HashMap

package com.wms.common;
import lombok.Data;

import java.util.HashMap;

@Data
public class QueryPageParam{
    //默认
    private static int PAGE_SIZE=20;
    private static int PAGE_NUM=1;
    private int pageSize=PAGE_SIZE;
    private int pageNum=PAGE_NUM;

    private HashMap parma;
}

usercontroller把parma部分改为query

@PostMapping("/listPage")
    public List<User>listPage(@RequestBody QueryPageParam query){
        System.out.println(query);
        //System.out.println("num==="+(String)map.get("pageSize"));

        System.out.println("num==="+query.getPageNum());
        System.out.println("size==="+query.getPageSize());
        /*LambdaQueryWrapper<User>LambdaQueryWrapper=newLambdaQueryWrapper();
        LambdaQueryWrapper.eq(User::getName,user.getName());
        return userService.list(LambdaQueryWrapper);*/

        return null;
    }

分页拦截器

 插件主体 | MyBatis-Plus     在com.wms.common下新建MybatisPlusConfig.java从网站中复制即可

package com.wms.common;

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;

@Configuration
//@MapperScan("com.wms")
public class MybatisPlusConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

这其实不乱好吧,1.Page是设置页码和尺寸的,2.Lam...是得到你的数据(此时还没进行真正的分页),3.IPage才是对数据进行分页的操作,结果保存在IPage对象中(这里是result);返回结果是[]的同学看看自己json的pageNum是不是1,因为数据库记录个数不够的话,其他页是没有数据的;如果查的数据是全部,可能是拦截器出问题了,换到3.4.1的拦截器;total等于零是因为MybatisPlusConfig类没有写

 @PostMapping("/listPage")
    //public List<User>listPage(@RequestBody HashMap map){
    public List<User>listPage(@RequestBody QueryPageParam query) {
        HashMap param = query.getParam();
        String name = (String) param.get("name");
        System.out.println("name===" + (String) param.get("name"));
        /*System.out.println("no==="+(String)param.get("no"));*/
            /*LambdaQueryWrapper<User>LambdaQuer[Wrapper=newLambdaQueryWrapper();
            lambdaQueryWrapper.eq(User::getName,user.getName());

            return userService.list(lambdaQueryllrapper);*/
        Page<User> page = new Page();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.like(User::getName, name);

        IPage result=userService.page(page,lambdaQueryWrapper);

        System.out.println("result=="+result.getTotal());


        return result.getRecords();
    }

当我想自己封装一个方法时, (之前是自带的方法  现在是自己写的 )

 在userservice导入pageC

package com.wms.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wms.entity.User;
import com.baomidou.mybatisplus.extension.service.IService;

/**
 * <p>
 *  服务类
 * </p>
 *
 * @author wms
 * @since 2024-11-19
 */
public interface UserService extends IService<User> {

    IPage pageC(IPage<User> page);
}

在userServiceImpl中导入(对于UserserviceImpl的红色,右键选择第一个PageC的于是userserviceIpml变成这样

package com.wms.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wms.entity.User;
import com.wms.mapper.UserMapper;
import com.wms.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wms
 * @since 2024-11-19
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;
    @Override
    public IPage pageC(IPage<User> page) {
        return userMapper.pageC(page);
    }
}

 同期UserController补充如下

@PostMapping("/listPageC")
    //public List<User>listPage(@RequestBody HashMap map){
    public List<User>listPageC(@RequestBody QueryPageParam query) {
        HashMap param = query.getParam();
        String name = (String) param.get("name");
        System.out.println("name===" + (String) param.get("name"));

        Page<User> page = new Page();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

       /* LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.like(User::getName, name);*/

        IPage result=userService.pageC(page);

        System.out.println("result=="+result.getTotal());


        return result.getRecords();
    }

插件自然修改usermapper.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.wms.mapper.UserMapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.wms.entity.User">
        <id column="id" property="id" />
        <result column="no" property="no" />
        <result column="name" property="name" />
        <result column="password" property="password" />
        <result column="age" property="age" />
        <result column="sex" property="sex" />
        <result column="phone" property="phone" />
        <result column="role_id" property="roleId" />
        <result column="isvalid" property="isvalid" />
    </resultMap>

    <!-- 通用查询结果列 -->
    <sql id="Base_Column_List">
        id, no, name, password, age, sex, phone, role_id, isvalid
    </sql>

    <select id="pageC" resultType="com.wms.entity.User">
        select * from user
    </select>
</mapper>

删除xml的pageC的那句

resultType="com.wms.entity.User"

 居然在usermappper.java报错的情况下成功运行了,但是在Navicat报错了

多方修改 ,将usermapper.java修改,即加一个<User>

IPage <User> pageC(IPage<User> page);

 成功运行

为了保证你有正确的结果我将提供5个代码

package com.wms.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wms.common.QueryPageParam;
import com.wms.entity.User;
import com.wms.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wms
 * @since 2024-11-19
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/list")
    public List<User> list() {
        return userService.list();
    }

    //新增
    @PostMapping("/save")
    public boolean save(@RequestBody User user) {
        return userService.save(user);
    }

    //修改
    @PostMapping("/mod")
    public boolean mod(@RequestBody User user) {
        return userService.updateById(user);
    }

    //新增或修改
    @PostMapping("/saveOrMod")
    public boolean saveOrMod(@RequestBody User user) {
        return userService.saveOrUpdate(user);
    }

    //删除
    @GetMapping("/delete")
    public boolean delete(Integer id) {
        return userService.removeById(id);
    }

    //查询(模糊、匹配)
    @PostMapping("/listP")
    public List<User> listP(@RequestBody User user) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.like(User::getName, user.getName());
        //lambdaQueryWrapper.eq(User::getName, user.getName());
        //eq就是完全匹配
        return userService.list(lambdaQueryWrapper);
    }

    @PostMapping("/listPage")
    //public List<User>listPage(@RequestBody HashMap map){
    public List<User>listPage(@RequestBody QueryPageParam query) {
        HashMap param = query.getParam();
        String name = (String) param.get("name");
        System.out.println("name===" + (String) param.get("name"));
        /*System.out.println("no==="+(String)param.get("no"));*/
            /*LambdaQueryWrapper<User>LambdaQuer[Wrapper=newLambdaQueryWrapper();
            lambdaQueryWrapper.eq(User::getName,user.getName());

            return userService.list(lambdaQueryllrapper);*/
        Page<User> page = new Page();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.like(User::getName, name);

        IPage result=userService.page(page,lambdaQueryWrapper);

        System.out.println("result=="+result.getTotal());


        return result.getRecords();
    }

    @PostMapping("/listPageC")
    //public List<User>listPage(@RequestBody HashMap map){
    public List<User>listPageC(@RequestBody QueryPageParam query) {
        HashMap param = query.getParam();
        String name = (String) param.get("name");
        System.out.println("name===" + (String) param.get("name"));

        Page<User> page = new Page();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

       /* LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.like(User::getName, name);*/

        IPage result=userService.pageC(page);

        System.out.println("result=="+result.getTotal());


        return result.getRecords();
    }
}
package com.wms.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wms.entity.User;
import com.wms.mapper.UserMapper;
import com.wms.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wms
 * @since 2024-11-19
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;
    @Override
    public IPage pageC(IPage<User> page) {
        return userMapper.pageC(page);
    }
}
package com.wms.mapper;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wms.entity.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;

/**
 * <p>
 *  Mapper 接口
 * </p>
 *
 * @author wms
 * @since 2024-11-19
 */
@Mapper
public interface UserMapper extends BaseMapper<User> {

    IPage <User> pageC(IPage<User> page);
}
<?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.wms.mapper.UserMapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.wms.entity.User">
        <id column="id" property="id" />
        <result column="no" property="no" />
        <result column="name" property="name" />
        <result column="password" property="password" />
        <result column="age" property="age" />
        <result column="sex" property="sex" />
        <result column="phone" property="phone" />
        <result column="role_id" property="roleId" />
        <result column="isvalid" property="isvalid" />
    </resultMap>

    <!-- 通用查询结果列 -->
    <sql id="Base_Column_List">
        id, no, name, password, age, sex, phone, role_id, isvalid
    </sql>

    <select id="pageC" resultType="com.wms.entity.User">
        select * from user
    </select>
</mapper>
package com.wms.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wms.entity.User;
import com.baomidou.mybatisplus.extension.service.IService;

/**
 * <p>
 *  服务类
 * </p>
 *
 * @author wms
 * @since 2024-11-19
 */
public interface UserService extends IService<User> {

    IPage pageC(IPage<User> page);
}

 如果我们自定义SQL用wrapper会非常方便,不用再写什么select * from user where name = ' '? 

使用 Wrapper 自定义 SQL | MyBatis-Plus

修改pageCC并且把lambdaquerywrapper加入(注释解放)usercontroller.java

@PostMapping("/listPageC")
    //public List<User>listPage(@RequestBody HashMap map){
    public List<User>listPageCC(@RequestBody QueryPageParam query) {
        HashMap param = query.getParam();
        String name = (String) param.get("name");
        System.out.println("name===" + (String) param.get("name"));

        Page<User> page = new Page();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.like(User::getName, name);


        //IPage result=userService.pageC(page);
        IPage result=userService.pageCC(page,lambdaQueryWrapper);
        System.out.println(total=="+result.getTotal());


        return result.getRecords();
    }

userservice.java  选择baomidou的那个方法类

public interface UserService extends IService<User> {

    IPage pageC(IPage<User> page);

    IPage pageCC (IPage<User> page,Wrapper<User> wrapper);
}

 userserviceimpl选择pagecc就自动生成的了

还是userserviceimpl中,根据 官网return相应的数据,并“在usermapper中创建方法pageCC”

usermapper中选择select statement 。跳转到usermapper.xml中,usermapper.java部分代码如下

@Mapper
public interface UserMapper extends BaseMapper<User> {

    IPage <User> pageC(IPage<User> page);

    IPage pageCC(IPage<User> page, @Param(Constants.WRAPPER)Wrapper<User> wrapper);
}

 写完xml中的部分如下

<select id="pageCC" resultType="com.baomidou.mybatisplus.core.metadata.IPage">
        select * from user ${ew.customSqlSegment}
    </select>

成功使用,调用的接口是/user/pageC 但里面的方法是pageCC 所以用的就是pageCC方法

这里教了3个方法,一个是默认生成的,一个是写的依赖,select * from xxx的,一个是自己写的select * from XXX where xxx;分页和查询条件的结合返回符合条件的分页信息,

六、返给前端数据的封装 

让前端收到统一的数据,方便处理

{
    Code:200//400
    Msg:"成功、失败”,
    Total:10
    Data:[] {}
}

在com.wms.common下新建一个类Result

package com.wms.common;

import lombok.Data;

@Data
public class Result {
    private int code;//200 or 400
    private String msg;//true or false
    private Long total;//总记录数
    private Object data;//data

    public static Result fail(){
        return result(400,"失败",0L,null);
    }
    public static Result success(){
        return result(200,"成功",0L,null);
    }
    public static Result success(Object data){
        return result(200,"成功",0L,data);
    }
    public static Result success(Object data,Long total){
        return result(200,"成功",total,data);
    }


    private static Result result(int code, String msg, Long total, Object data) {
           Result res = new Result();
           res.setData(data);
           res.setMsg(msg);
           res.setCode(code);
           res.setTotal(total);
           return res;

    }
}

Usercontroller新加一个方法

@PostMapping("/listPageC1")
    //public List<User>listPage(@RequestBody HashMap map){
    public Result listPageC1(@RequestBody QueryPageParam query) {
        HashMap param = query.getParam();
        String name = (String) param.get("name");
        System.out.println("name===" + (String) param.get("name"));

        Page<User> page = new Page();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.like(User::getName, name);


        //IPage result=userService.pageC(page);
        IPage result=userService.pageCC(page,lambdaQueryWrapper);
        System.out.println("total=="+result.getTotal());


        return Result.success(result.getRecords(),result.getTotal());
    }

非常伤心,失败了

根据提供的信息,问题出在MyBatis Plus尝试通过反射创建IPage对象时找不到无参构造函数。这是一个常见的问题,通常是由于配置或使用方式不正确引起的。

分析与解决方案
1. 检查IPage的使用
在您的XML映射文件中,pageCC方法的返回类型被设置为IPage,这是不正确的。IPage是一个接口,而不是具体的实现类。MyBatis Plus在处理分页查询时,会自动将结果封装到具体的分页对象中,例如Page。

2. 修改XML映射文件
将pageCC方法的返回类型从IPage改为具体的实体类型,例如User。

嗷嗷修改部分xml如下,成功运行!!

<select id="pageCC" resultType="com.wms.entity.User"><!--com.baomidou.mybatisplus.core.metadata.IPage-->
        select * from user ${ew.customSqlSegment}
    </select>

;