springboot+mybatisplus+vue 宿舍管理项目

0.前言

此项目为新手练手项目,包含springboot mybatis-pules vue等
Jdk1.8 ++ Mysql 8.0

项目技术:

Springboot + Maven + Mybatisplus + Vue 等等组成

1、搭建前端VUE环境

前提要先搭建vue所需要的环境

1、创建vue

1.在命令行输入vue ui 进入

在这里插入图片描述

2.选择你要在那给目录下创建并点击创建:

在这里插入图片描述

3.输入项目名称

在这里插入图片描述

4.选择创建模式

在这里插入图片描述

5.选择特色

在这里插入图片描述

6、选择版本

在这里插入图片描述

7.添加项目要用到的插件一个是element 一个是axios与后端交互要用到的

在这里插入图片描述

完成后通过idea打开刚才创建好的项目

在这里插入图片描述

至此vue环境初步已经搭建完成下面就开始编写具体实现代码

2.登录代码部分

1.删除App.vue下部分内容,添加

2.在views下创建一个Login.vue

代码如下:

<template>
    <div class="login-container">
        <el-form :model="ruleForm" :rules="rules"
                 status-icon
                 ref="ruleForm"
                 label-position="left"
                 label-width="0px"
                 class="demo-ruleForm login-page">
            <h3 class="title">系统登录</h3>
            <el-form-item prop="username">
                <el-input type="text"
                          v-model="ruleForm.username"
                          placeholder="用户名"
                ></el-input>
            </el-form-item>
            <el-form-item prop="password">
                <el-input type="password"
                          v-model="ruleForm.password"
                          placeholder="密码"
                ></el-input>
            </el-form-item>
            <el-form-item>
                <el-radio v-model="type" label="systemAdmin">系统管理员</el-radio>
                <el-radio style="position: relative;left: 80px" v-model="type" label="dormitoryAdmin">宿舍管理员</el-radio>
            </el-form-item>
            <el-form-item style="width:100%;">
                <el-button type="primary" style="width:100%;" @click="handleSubmit" :loading="logining">登录</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
    export default {
        name: "Login",
        data() {
            return {
                logining: false,
                ruleForm: {
                    username: 'admin',
                    password: '123'
                },
                type: 'systemAdmin',
                rules: {
                    username: [{required: true, message: '请输入用户名', trigger: 'blur'}],
                    password: [{required: true, message: '请输入密码', trigger: 'blur'}]
                }
            }
        },
       
</script>

<style scoped>
    .login-container {
        width: 100%;
        height: 100%;
    }

    .login-page {
        -webkit-border-radius: 5px;
        border-radius: 5px;
        margin: 180px auto;
        width: 350px;
        padding: 35px 35px 15px;
        background: #fff;
        border: 1px solid #eaeaea;
        box-shadow: 0 0 25px #cac6c6;
    }

    label.el-checkbox.rememberme {
        margin: 0px 0px 15px;
        text-align: left;
    }
</style>

这些是添加element模板插件改的地址:https://element.eleme.cn/#/zh-CN/component/form

3.给它加入到index.js路游里,引入路游

在这里插入图片描述

这个的原理如下图所示

在这里插入图片描述

就是所写的页面注册到router/index.js中,由他去切换到App.vue上

前端页面展示:
在这里插入图片描述
在这里插入图片描述

2、后端springboot实现

1、后端环境搭建

1.新建springboot项目

2.添加依赖

<dependencies>
        <!--springboot-web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--mysql-->
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <version>8.0.31</version>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
        </dependency>
        <!--springboot-test-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>2.7.0</version>
        </dependency>
        <!--mybatis-plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.2</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
            <version>1.7</version>
        </dependency>
        <!--log4j-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>

3.创建一个mybatis-plus的生成器

package com.lsa;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

public class Main {
    public static void main(String[] args) {
        //创建对象
        AutoGenerator autoGenerator = new AutoGenerator();
        //数据源
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDbType(DbType.MYSQL);
        dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
        dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/dormitory");
        dataSourceConfig.setUsername("root");
        dataSourceConfig.setPassword("123456789");
        autoGenerator.setDataSource(dataSourceConfig);
        //全局配置
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setOutputDir(System.getProperty("user.dir") + "/src/main/java");
        globalConfig.setAuthor("admin");
        globalConfig.setOpen(false);
        //去掉Service的I
        globalConfig.setServiceName("%sService");
        autoGenerator.setGlobalConfig(globalConfig);
        //包配置
        PackageConfig packageConfig = new PackageConfig();
        packageConfig.setParent("com.lsa.southwind");
        packageConfig.setEntity("entity");
        packageConfig.setMapper("mapper");
        packageConfig.setService("service");
        packageConfig.setServiceImpl("service.impl");
        packageConfig.setController("controller");
        packageConfig.setModuleName(null);
        autoGenerator.setPackageInfo(packageConfig);
        //策略配置
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig.setInclude("absent", "building", "dormitory", "dormitory_admin", "moveout", "student", "system_admin");
        strategyConfig.setNaming(NamingStrategy.underline_to_camel);
        strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);
        strategyConfig.setEntityLombokModel(true);
        autoGenerator.setStrategy(strategyConfig);
        //启动
        autoGenerator.execute();
    }

}

首先:

1.创建AutoGenerator()对象

2.配置数据源

3.全局配置:

  • globalConfig.setOutputDir(System.getProperty(“user.dir”) + “/src/main/java”);

  • “user.dir"放在根目录下哪个位置,具体位置:”/src/main/java"

  • globalConfig.setOpen(false)是否打开文件这里写的是不打开

  • globalConfig.setServiceName(“%sService”);

    为什么用这个呢,因为mybatis-plus会主动把我们的service文件默认为,I类名Service这样的

    如下下图:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5Dx7tJzR-1679833859348)(C:\Users\卢申澳\Desktop\上课笔记\JAVA全栈\springboot+vue项目\img\1677297101606.jpg)]

%s就是去掉前面哪个I

4.包配置创建包:PackageConfig packageConfig = new PackageConfig();

5.策略机制StrategyConfig strategyConfig = new StrategyConfig();

  • strategyConfig.setInclude():里面的参数写数据库的表名

  • strategyConfig.setNaming(NamingStrategy.underline_to_camel);
    strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);

驼峰的转换

运行后

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XoBnj7RV-1679833859356)(C:\Users\卢申澳\Desktop\上课笔记\JAVA全栈\springboot+vue项目\img\1677316616007.jpg)]

2、前后端登录对接

这里我们需要添加两个实体类,ResultVO和RuleForm两个类

ResultVO用了存放判断的结果,

package com.lsa.southwind.vo;

import lombok.Data;

@Data
public class ResultVo<T> {
    private Integer code;
    private T data;
}

RuleForm用来定义前端传递过来的数据

package com.lsa.southwind.form;
import lombok.Data;
@Data
public class RuleForm {
    private String username;
    private String password;
}

编写具体实现代码

因为用到了QueryWrapper不用再去编写具体的sql代码

serviceimpl:

package com.lsa.southwind.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lsa.southwind.entity.SystemAdmin;
import com.lsa.southwind.form.RuleForm;
import com.lsa.southwind.mapper.SystemAdminMapper;
import com.lsa.southwind.service.SystemAdminService;
import com.lsa.southwind.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author admin
 * @since 2023-02-25
 */
@Service
public class SystemAdminServiceImpl extends ServiceImpl<SystemAdminMapper, SystemAdmin> implements SystemAdminService {
    @Autowired
    private SystemAdminMapper systemAdminMapper;

    @Override
    public ResultVo login(RuleForm ruleForm) {
        //1.判读用户名是否存在
        //使用querywrapper去判断
        QueryWrapper<SystemAdmin> queryWrapper = new QueryWrapper<>();
        //这里.eq("数据库表的列名","要比较的值")
        queryWrapper.eq("username", ruleForm.getUsername());
        SystemAdmin systemAdmin = this.systemAdminMapper.selectOne(queryWrapper);
        ResultVo resultVo = new ResultVo();
        if (systemAdmin == null) {
            //如果查询出来为空,说明用户不存在
            resultVo.setCode(-1);
        } else {
            //2.判断密码所示否正确
            if (!systemAdmin.getPassword().equals(ruleForm.getPassword())) {
                resultVo.setCode(-2);
            } else {
                resultVo.setCode(0);
                resultVo.setData(systemAdmin);
            }
        }
        return resultVo;
    }
}

controller:


package com.lsa.southwind.controller;


import com.lsa.southwind.form.RuleForm;
import com.lsa.southwind.service.SystemAdminService;
import com.lsa.southwind.vo.ResultVo;
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;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author admin
 * @since 2023-02-25
 */
@RestController
@RequestMapping("/systemAdmin")
public class SystemAdminController {
    @Autowired
    private SystemAdminService systemAdminService;

    @GetMapping("/login")
    public ResultVo login(RuleForm ruleForm) {
        ResultVo resultVologin = this.systemAdminService.login(ruleForm);
        System.out.println(resultVologin);
        return resultVologin;
    }
}

到这里后端的登录代码也基本已经写完,

前端Vue交互代码:

 methods: {
            handleSubmit() {
                this.$refs.ruleForm.validate((valid) => {
                    if (valid) {
                        this.logining = true
                        let _this = this
                        if (_this.type == 'dormitoryAdmin') {
                            axios.get('http://localhost:8181/dormitoryAdmin/login', {params: _this.ruleForm}).then(function (resp) {
                                _this.logining = false
                                if (resp.data.code == -1) {
                                    _this.$alert('用户名不存在', '提示', {
                                        confirmButtonText: '确定'
                                    })
                                }
                                if (resp.data.code == -2) {
                                    _this.$alert('密码错误', '提示', {
                                        confirmButtonText: '确定'
                                    })
                                }
                                if (resp.data.code == 0) {
                                    //跳转到SystemAdmin
                                    //展示当前登录用户信息
                                    localStorage.setItem('dormitoryAdmin', JSON.stringify(resp.data.data));
                                    _this.$router.replace({path: '/dormitoryAdmin'})
                                }
                            })
                        }
                        if (_this.type == 'systemAdmin') {
                            axios.get('http://localhost:8181/systemAdmin/login', {params: _this.ruleForm}).then(function (resp) {
                                _this.logining = false
                                if (resp.data.code == -1) {
                                    _this.$alert('用户名不存在', '提示', {
                                        confirmButtonText: '确定'
                                    })
                                }
                                if (resp.data.code == -2) {
                                    _this.$alert('密码错误', '提示', {
                                        confirmButtonText: '确定'
                                    })
                                }
                                if (resp.data.code == 0) {
                                    //跳转到SystemAdmin
                                    //展示当前登录用户信息
                                    localStorage.setItem('systemAdmin', JSON.stringify(resp.data.data));
                                    _this.$router.replace({path: '/systemAdmin'})
                                }
                            })
                        }
                    }
                })
            }
        }
    };

现在只需要前端交互即可,在具体实现的时候遇到了一个问题就是VUE与springboot跨区域的问题,这里我们直接用一个工具类去实现

package com.lsa.southwind.configuration;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CrosConfiguration implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }

}

测试一个不存在可以看到data里也有返回的数据

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fTG5Vali-1679833859357)(C:\Users\卢申澳\Desktop\上课笔记\JAVA全栈\springboot+vue项目\img\1677318018938.jpg)]

另一个登录与它相似不在编写

3、前端菜单搭建

首先来一个完成后的图

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cKiO9GXR-1679833859357)(C:\Users\卢申澳\Desktop\上课笔记\JAVA全栈\springboot+vue项目\img\1677397118968.jpg)]

布局结构图

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-R9OM1CTV-1679833859358)(C:\Users\卢申澳\Desktop\上课笔记\JAVA全栈\springboot+vue项目\img\1677397485964.jpg)]

我通过Element来搭建框架

Element地址:https://element.eleme.cn/#/zh-CN/component/menu

登录成功后跳转到SystemAdmin页面

SystemAdmin.vue

<template>
    <!--头部Header-->
    <el-container class="home_container">
        <el-header class="home_header">
            <div class="home_title">DORMS宿舍管理系统-系统管理员</div>
            <div class="home_userinfoContainer">
                <el-dropdown>
                  <span class="el-dropdown-link home_userinfo">
                    {{admin.name}}<i class="el-icon-arrow-down el-icon--right home_userinfo"></i>
                  </span>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item @click.native="logout">退出登录</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </div>
        </el-header>
        <!--侧边aside-->
        <el-container>
            <el-aside class="home_aside" width="200px">
                <el-menu router>
                    <el-submenu index="1"><!-- index="1"可以打开下拉框-->
                        <template slot="title">
                            <i class="el-icon-s-platform"></i>宿管模块
                        </template>
                        <el-menu-item index="/dormitoryAdminAdd"
                                      :class="$route.path=='/dormitoryAdminAdd'?'is-active':''"><!--不可以打开-->
                            <!--三元表达式:class="$route.path=='/dormitoryAdminAdd'?'is-active':''
                                判断  $route.path=='/dormitoryAdminAdd'
                                如果为 true则 选择  is-active
                                如果为 false则 ''
                            -->
                            <i class="el-icon-folder-add"></i>添加宿管
                        </el-menu-item>
                        <el-menu-item index="/dormitoryAdminManager"
                                      :class="$route.path=='/dormitoryAdminManager'?'is-active':''">
                            <i class="el-icon-document-copy"></i>宿管管理
                        </el-menu-item>
                    </el-submenu>
                    <!--学生模块-->
                    <el-submenu index="2">
                        <template slot="title">
                            <i class="el-icon-user-solid"></i>学生模块
                        </template>
                        <el-menu-item index="/studentAdd" :class="$route.path=='/studentAdd'?'is-active':''">
                            <i class="el-icon-folder-add"></i>添加学生
                        </el-menu-item>
                        <el-menu-item index="/studentManager">
                            <i class="el-icon-document-copy"></i>学生管理
                        </el-menu-item>
                    </el-submenu>
                    <!--楼宇模块-->
                    <el-submenu index="3">
                        <template slot="title"><i class="el-icon-s-grid"></i>楼宇模块</template>
                        <el-menu-item index="/buildingAdd">
                            <i class="el-icon-folder-add"></i>添加楼宇
                        </el-menu-item>
                        <el-menu-item index="/buildingManager">
                            <i class="el-icon-document-copy"></i>楼宇管理
                        </el-menu-item>
                    </el-submenu>
                    <!--宿舍模块-->
                    <el-submenu index="4">
                        <template slot="title"><i class="el-icon-s-home"></i>宿舍模块</template>
                        <el-menu-item index="/dormitoryAdd">
                            <i class="el-icon-folder-add"></i>添加宿舍
                        </el-menu-item>
                        <el-menu-item index="/dormitoryManager">
                            <i class="el-icon-document-copy"></i>宿舍管理
                        </el-menu-item>
                    </el-submenu>

                    <el-menu-item index="/moveoutRegister">
                        <i class="el-icon-s-unfold"></i>
                        <span slot="title">学生迁出登记</span>
                    </el-menu-item>

                    <el-menu-item index="/moveoutRecord">
                        <i class="el-icon-s-order"></i>
                        <span slot="title">学生迁出记录</span>
                    </el-menu-item>

                    <el-menu-item index="/absentRecord">
                        <i class="el-icon-error"></i>
                        <span slot="title">学生缺寝记录</span>
                    </el-menu-item>
                </el-menu>
            </el-aside>
            <!--内容Main-->
            <el-container>
                <el-main>
                    <el-breadcrumb separator-class="el-icon-arrow-right">
                        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                        <el-breadcrumb-item v-text="this.$router.currentRoute.name"></el-breadcrumb-item>
                    </el-breadcrumb>
                    <router-view></router-view>
                </el-main>
                <el-footer class="home_footer">2023 © DORMS-lsa</el-footer>
            </el-container>
        </el-container>
    </el-container>
</template>
<script>
    export default {
        methods: {
            logout() {
                let _this = this;
                this.$confirm('注销登录吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(function () {
                    localStorage.removeItem('systemAdmin')
                    _this.$router.replace({path: '/'})
                })
            }
        },
        data() {
            return {
                admin: ''
            }
        },
        created() {
            /*跳转后取出存入的数据把string转为JSON*/
            let admin = JSON.parse(window.localStorage.getItem('systemAdmin'))
            this.admin = admin
        }
    }
</script>
<style>

    .home_container {
        height: 100%;
        position: absolute;
        top: 0px;
        left: 0px;
        width: 100%;
    }

    .home_header {
        background-color: #2B2B2B;
        text-align: center;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .home_title {
        color: #C2C2C2;
        font-size: 22px;
        display: inline;
    }

    .home_userinfo {
        color: #fff;
        cursor: pointer;
    }

    .home_userinfoContainer {
        display: inline;
        margin-right: 20px;
    }

    .home_aside {
        background-color: #FFFFFF;
    }

    .home_footer {
        background-color: #FFFFFF;
        color: #000000;
        font-size: 18px;
        line-height: 60px;
        text-align: center;
    }
</style>

这里值得注意的时有一个三元表达式,我们也添加了两个页面让他去跳转

创建完页面后要加到路游里,因为显示在Systemadmin所有路游要创建到它的下面:

 {
        path: '/systemAdmin',
        name: '宿舍管理员',
        component: SystemAdmin,
        children: [
            {
                path: '/dormitoryAdminAdd',
                name: '添加宿舍',
                component: DormitoryAdminAdd
            },
            {
                path: '/dormitoryAdminManager',
                name: '宿舍管理',
                component: DormitoryAdminManager
            }
        ]
    }

4、宿管模块

1.宿管模块的添加

首先搭建宿舍页面

DormitoryAdminAdd.vue

<template>
    <div style="margin-top: 60px;margin-left:330px;width: 300px;height: 500px;border: 0px solid #7700ff;">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="ruleForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="ruleForm.password"></el-input>
            </el-form-item>
            <el-form-item label="姓名" prop="name">
                <el-input v-model="ruleForm.name"></el-input>
            </el-form-item>
            <el-form-item label="性别">
                <div style="width: 170px;height: 30px;">
                    <template>
                        <el-radio v-model="ruleForm.gender" label="男">男</el-radio>
                        <el-radio v-model="ruleForm.gender" label="女">女</el-radio>
                    </template>
                </div>
            </el-form-item>
            <el-form-item label="联系电话" prop="telephone">
                <el-input v-model.number="ruleForm.telephone"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
                <el-button @click="resetForm('ruleForm')">重置</el-button>
            </el-form-item>
        </el-form>
    </div>

</template>
<script>
    export default {
        data() {
            return {
                category: null,
                /*Model双向绑定*/
                ruleForm: {
                    username: '',
                    password: '',
                    name: '',
                    gender: '男',
                    telephone: ''
                },
                rules: {
                    username: [
                        {required: true, message: '请输入用户名', trigger: 'blur'}
                    ],
                    password: [
                        {required: true, message: '请输入密码', trigger: 'blur'}
                    ],
                    name: [
                        {required: true, message: '请输入姓名', trigger: 'blur'}
                    ],
                    telephone: [
                        {required: true, message: '请输入联系电话', trigger: 'blur'}
                    ]
                }
            };
        },
        methods: {
            submitForm(formName) {
                const _this = this
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        console.log(_this.ruleForm)
                        axios.post('http://localhost:8181/dormitoryAdmin/save', _this.ruleForm).then(function (resp) {
                            if (resp.data.code == 0) {
                                console.log(resp)
                                _this.$alert(_this.ruleForm.username + '添加成功', '', {
                                    confirmButtonText: '确定',
                                    callback: action => {
                                        _this.$router.push('/dormitoryAdminManager')
                                    }
                                });
                            }
                        })
                    }
                });
            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
            }
        }
    }
</script>
<style>

</style>

2.宿管信息的展示以及数据的分页查询

首先把前端页面构建完成,也是通过element去创建的

<template>
    <div style="margin-top: 60px;margin-left:80px;border: 0px solid red;">
        <el-form style="margin-left: -40px" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px"
                 class="demo-ruleForm">
            <el-form-item label="字段:" prop="key">
                <el-select v-model="ruleForm.key" style="width: 160px;float: left" placeholder="请选择字段">
                    <el-option label="宿管账号" value="username"></el-option>
                    <el-option label="宿管姓名" value="name"></el-option>
                    <el-option label="宿管电话" value="telephone"></el-option>
                </el-select>
            </el-form-item>
            <div style="border: 0px solid red;width: 400px;height: 60px;position: relative;top: -64px;left: 270px">
                <el-form-item label="值:">
                    <el-input v-model="ruleForm.value" placeholder="请输入关键字" style="width: 160px;"></el-input>
                    <el-button type="primary" icon="el-icon-search" style="position: relative;left: 10px;"
                               @click="submitForm('ruleForm')">搜索
                    </el-button>
                </el-form-item>
            </div>
        </el-form>

        <el-table
                :data="tableData"
                border
                stripe
                style="width: 100%;position: relative;top:-30px">
            <!--列名-->
            <el-table-column
                    fixed
                    prop="id"
                    label="ID"
                    width="160">
            </el-table-column>
            <el-table-column
                    prop="username"
                    label="用户名"
                    width="160">
            </el-table-column>
            <el-table-column
                    prop="password"
                    label="密码"
                    width="160">
            </el-table-column>
            <el-table-column
                    prop="name"
                    label="姓名"
                    width="160">
            </el-table-column>
            <el-table-column
                    prop="gender"
                    label="性别"
                    width="160">
            </el-table-column>
            <el-table-column
                    prop="telephone"
                    label="联系电话"
                    width="160">
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button
                            size="mini"
                            @click="edit(scope.row)">编辑
                    </el-button>
                    <el-button
                            size="mini"
                            type="danger"
                            @click="del(scope.row)">删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination style="margin-top: 20px;float: right"
                       background
                       layout="prev, pager, next"
                       :page-size="pageSize"
                       :total="total"
                       :current-page.sync="currentPage"
                       @current-change="page">
        </el-pagination>
    </div>

</template>

<script>
    export default {
        data() {
            return {
                tableData: null,
                currentPage: 1,
                pageSize: 3,
                total: '',
                key: '',
                value: '',
                ruleForm: {
                    key: '',
                    value: '',
                    page: '',
                    size: 3
                },
                rules: {
                    key: [
                        {required: true, message: '请选择字段', trigger: 'change'}
                    ]
                }
            }
        },
        methods: {
         
        created() {
            const _this = this
            /*提交到后台*/
            axios.get('http://localhost:8181/dormitoryAdmin/list/' + _this.currentPage + '/' + _this.pageSize).then(function (resp) {
                console.log(resp)
                _this.tableData = resp.data.data.data
                _this.total = resp.data.data.total
            })

        }
    }
</script>

其中主要的信息就是

tableData: 是页面中的数据信息从后端把数据回调过来后添加到上面

currentPage: 当前页数

pageSize: 一页显示多少个

total: 一共从数据库中查询出来多少条数据

key: 查询中的关键词

value: 输入要查询的内容

ruleForm: 创建的对象

后端代码

需要添加一个分页的配置类

package com.lsa.southwind.configuration;

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * <p>
 * 配置类
 * </p>
 *
 * @author admin
 * @since 2023-02-25
 */
@Configuration
public class PageConfiguration {

    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}

因为使用到了分页查询所有这里创建一个属于分页查询的VO

package com.lsa.southwind.vo;

import lombok.Data;

@Data
public class PageVo {
    private Object data;
    private Long total;
}

service:

  @Override
    public PageVo list(Integer page, Integer size) {
        /*分页查询 page页数,size大小*/
        Page<DormitoryAdmin> dormitoryAdminPage = new Page<>(page, size);
        Page<DormitoryAdmin> resultPage = this.dormitoryAdminMapper.selectPage(dormitoryAdminPage, null);
        PageVo pageVo = new PageVo();
        /*获取总条数*/
        pageVo.setTotal(resultPage.getTotal());
        pageVo.setData(resultPage.getRecords());
        return pageVo;
    }

这里用到了mybatins-plus的分页查询,把传递过来的数据进行封装后进行查询,查询出来的数据回填到创建好的pageVo中返回出去

3.宿管模块的搜索

在之前的管理页面进行操作

tableData: 是页面中的数据信息从后端把数据回调过来后添加到上面

currentPage: 当前页数

pageSize: 一页显示多少个

total: 一共从数据库中查询出来多少条数据

key: 查询中的关键词

value: 输入要查询的内容

ruleForm: 创建的对象

  submitForm(formName) {
                const _this = this
                //让翻页复原
                _this.currentPage = 1
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        const _this = this
                        _this.ruleForm.page = _this.currentPage
                        axios.get('http://localhost:8181/dormitoryAdmin/search', {params: _this.ruleForm}).then(function (resp) {
                            _this.tableData = resp.data.data.data
                            _this.total = resp.data.data.total
                        })
                    }
                });
            },
            page(currentPage) {
                const _this = this
                if (_this.ruleForm.value == '') {
                    axios.get('http://localhost:8181/dormitoryAdmin/list/' + currentPage + '/' + _this.pageSize).then(function (resp) {
                        _this.tableData = resp.data.data.data
                        _this.total = resp.data.data.total
                    })
                } else {
                    _this.ruleForm.page = _this.currentPage
                    axios.get('http://localhost:8181/dormitoryAdmin/search', {params: _this.ruleForm}).then(function (resp) {
                        _this.tableData = resp.data.data.data
                        _this.total = resp.data.data.total
                    })
                }
            },
            edit(row) {
                this.$router.push('/dormitoryAdminUpdate?id=' + row.id)
            },
            del(row) {
                const _this = this
                this.$confirm('确认删除【' + row.username + '】吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.delete('http://localhost:8181/dormitoryAdmin/deleteById/' + row.pageSize).then(function (resp) {
                        if (resp.data.code == 0) {
                            _this.$alert('【' + row.username + '】已删除', '', {
                                confirmButtonText: '确定',
                                callback: action => {
                                    location.reload()
                                }
                            });
                        }
                    });
                });
            }
        },

首先分析一下几个BUG,

  • 第显示为全部是我们点击到第二页去进行模糊查询会发现它还是显示在第二页没有跳转到第一页

    为什么会这样呢?

    因为我们的页面page没有更新

    所有我们让翻页复原:

_this.currentPage = 1

每次去点击搜索的时候就给它的页数赋值为1

  • 当我们模糊查询的时候一共4条数据,你点击第二页时候会发发现,它不知道我们是在查询下的分页还是非查询下的分页

    所有需要去判断是什么场景

    只需要判断value是否有值,没有值就是全部,有值则是模糊查询

4.宿管模块修改功能

当编辑按钮是我们让他触发

<el-button
   size="mini"
   @click="edit(scope.row)">编辑
</el-button>

然后去调用该方法跳转到指定页面去做操作

 /*修改*/
 edit(row) {
       /*提交到要跳转的路径+id*/
       this.$router.push('/dormitoryAdminUpdate?id=' + row.id)
           }

该页面dormitoryAdminUpdate.vue

<template>
    <div style="margin-top: 60px;margin-left:330px;width: 300px;height: 500px;border: 0px solid #7700ff;">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="ID">
                <el-input v-model="ruleForm.id" readonly></el-input>
            </el-form-item>
            <el-form-item label="用户名" prop="username">
                <el-input v-model="ruleForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="ruleForm.password"></el-input>
            </el-form-item>
            <el-form-item label="姓名" prop="name">
                <el-input v-model="ruleForm.name"></el-input>
            </el-form-item>
            <el-form-item label="性别">
                <div style="width: 170px;height: 30px;">
                    <template>
                        <el-radio v-model="ruleForm.gender" label="男">男</el-radio>
                        <el-radio v-model="ruleForm.gender" label="女">女</el-radio>
                    </template>
                </div>
            </el-form-item>
            <el-form-item label="联系电话" prop="telephone">
                <el-input v-model.number="ruleForm.telephone"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
                <el-button @click="resetForm('ruleForm')">重置</el-button>
            </el-form-item>
        </el-form>
    </div>

</template>
<script>
    export default {
        data() {
            return {
                category: null,
                /*Model双向绑定*/
                ruleForm: {
                    username: '',
                    password: '',
                    name: '',
                    gender: '男',
                    telephone: ''
                },
                rules: {
                    username: [
                        {required: true, message: '请输入用户名', trigger: 'blur'}
                    ],
                    password: [
                        {required: true, message: '请输入密码', trigger: 'blur'}
                    ],
                    name: [
                        {required: true, message: '请输入姓名', trigger: 'blur'}
                    ],
                    telephone: [
                        {required: true, message: '请输入联系电话', trigger: 'blur'}
                    ]
                }
            };
        },
        methods: {
            submitForm(formName) {
                const _this = this
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        console.log(_this.ruleForm)
                        axios.put('http://localhost:8181/dormitoryAdmin/update', _this.ruleForm).then(function (resp) {
                            if (resp.data.code == 0) {
                                console.log(resp)
                                _this.$alert(_this.ruleForm.username + '添加成功', '', {
                                    confirmButtonText: '确定',
                                    callback: action => {
                                        _this.$router.push('/dormitoryAdminManager')
                                    }
                                });
                            } else if (resp.data.code == -1) {
                                _this.$alert('注册失败', '提示', {
                                    confirmButtonText: '确认'
                                })
                            }
                        })
                    }
                });
            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
            }
        },
        /*接收管理页面提交过来的数据,提交到后台,不要写在methods方法中,接收跳转过来的数据的*/
        created() {
            const _this = this
            axios.get('http://localhost:8181/dormitoryAdmin/findById/' + _this.$route.query.id).then(function (resp) {
                _this.ruleForm = resp.data.data
            })
        }

    }
</script>

跳转到这个页面需要做两个与后台交互的操作,

1.就是刚传递过来的id去后台查询,查询后通过ruleForm绑定到前端上

 @GetMapping("/findById/{id}")
    public ResultVo findById(@PathVariable("id") Integer id) {
       
        DormitoryAdmin dormitoryAdmin = this.dormitoryAdminService.getById(id);
        return ResultVoUtil.success(dormitoryAdmin);

    }

2.就是前端修改完数据后提交到后端

    @DeleteMapping("/deleteById/{id}")
    public ResultVo delete(@PathVariable("id") Integer id) {
        boolean removeById = this.dormitoryAdminService.removeById(id);
        if (!removeById) {
            return ResultVoUtil.fail();
        } else {
            return ResultVoUtil.success(null);
        }
    }

5.宿管模块删除

前端

   del(row) {
                const _this = this
                this.$confirm('确认删除【' + row.username + '】吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.delete('http://localhost:8181/dormitoryAdmin/deleteById/' + row.id).then(function (resp) {
                        if (resp.data.code == 0) {
                            _this.$alert('【' + row.username + '】已删除', '', {
                                confirmButtonText: '确定',
                                callback: action => {
                                    location.reload()
                                }
                            });
                        }
                    });
                });
            }

后端

@DeleteMapping("/deleteById/{id}")
    public ResultVo delete(@PathVariable("id") Integer id) {
        boolean removeById = this.dormitoryAdminService.removeById(id);
        if (!removeById) {
            return ResultVoUtil.fail();
        } else {
            return ResultVoUtil.success(null);
        }
    }

5、学生模块

1.学生添加

前端vue和之前的宿舍添加几乎一样不在特别写出来了

后端因为涉及到学生宿舍人数的问题:

1.就是把宿舍有空位的查询出来

2.学生添加成功后,添加的宿舍人数减1

首先把宿舍有空位的查询出来

  @Autowired
    private DormitoryMapper dormitoryMapper;

    @Override
    public ResultVo availableList() {
        QueryWrapper<Dormitory> queryWrapper = new QueryWrapper<>();
        queryWrapper.ge("available", 1);
        List<Dormitory> dormitoryList = dormitoryMapper.selectList(queryWrapper);
        System.out.println("查询的数据:" + dormitoryList);
        if (dormitoryList == null) {
            return ResultVoUtil.fail();
        } else {

            return ResultVoUtil.success(dormitoryList);
        }

    }

下面就是学生的添加

  • controller
    @PostMapping("/save")
    public ResultVo saveStudent(@RequestBody Student student) {
        Boolean saveStudent = this.studentService.saveStudent(student);
        if (!saveStudent) {
            return ResultVoUtil.fail();
        } else {
            return ResultVoUtil.success(null);
  • service
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private DormitoryMapper dormitoryMapper;

    @Override
    public Boolean saveStudent(Student student) {
        //添加学生
        student.setCreateDate(CommonUtil.createDate());
        student.setState("入住");
        int insert = this.studentMapper.insert(student);
        if (insert != 1) {
            return false;
        } else {
            //添加成功,修改入住的宿舍的人数数量
            //1.先查看要入住的宿舍的数量,通过学生宿舍id去查询该宿舍的全部信息
            Dormitory dormitory = this.dormitoryMapper.selectById(student.getDormitoryId());
            //2.判断要入住的宿舍的人数
            if (dormitory.getAvailable() == 0) {
                return false;
            } else {
                dormitory.setAvailable(dormitory.getAvailable() - 1);
                int updateById = this.dormitoryMapper.updateById(dormitory);
                if (updateById != 1) {
                    return false;
                }
                return true;
            }
        }
    }

后端逻辑完成

2.学生信息展示及分页查询

前端代码:

     created() {
            const _this = this
            axios.get('http://localhost:8181/student/list/' + _this.currentPage + '/' + _this.pageSize).then(function (resp) {
                _this.tableData = resp.data.data.data
                _this.total = resp.data.data.total
            })
        }

提交到后端的地址,

因为前端要展示的数据与数据库不同,前端要展示的宿舍号,而数据库查询出来的宿舍的id

所以后端要定义一个StudentVo与前端数据对应:

@Data
public class StudentVo {
    private Integer id;
    private String number;
    private String name;
    private String gender;
    private String dormitoryName;
    private String state;
    private String createDate;
}
  • controller
    @GetMapping("/list/{page}/{size}")
    public ResultVo listStudent(@PathVariable("page") Integer page, @PathVariable("size") Integer size) {
        PageVo studentlist = this.studentService.list(page, size);
        return ResultVoUtil.success(studentlist);
    }
  • service
 /*学生页面查询*/
    @Override
    public PageVo list(Integer page, Integer size) {
        /*分页查询 page页数,size大小*/
        Page<Student> studentListPage = new Page<>(page, size);
        Page<Student> resultPage = this.studentMapper.selectPage(studentListPage, null);
        /*因为前端要的是宿舍名,而我们后端查询出来的是宿舍的id所有我们要把他转化一下*/
        List<Student> studentList = resultPage.getRecords();
        //将Vo转换
        List<StudentVo> studentVoList = new ArrayList<>();
        /*通过遍历studentList*/
        for (Student student : studentList) {
            /*前端需要的实体类*/
            StudentVo studentVo = new StudentVo();
            /*属性的复制 左边为被复制的属性,右边是目标属性*/
            BeanUtils.copyProperties(student, studentVo);
            /*现在根据学生的宿舍id查出宿舍名*/
            Dormitory dormitory = this.dormitoryMapper.selectById(student.getDormitoryId());
            studentVo.setDormitoryName(dormitory.getName());
            studentVoList.add(studentVo);

        }
        PageVo pageVo = new PageVo();
        /*获取总条数*/
        pageVo.setTotal(resultPage.getTotal());
        /*存入查出的数据*/
        System.out.println("查询出的数据:" + studentVoList);
        pageVo.setData(studentVoList);
        return pageVo;
    }

代码总体解释分析:

1.首先是分页,通过分页信息查询出

2.遍历查询出来的学生信息,因为与前端数据不对应

3.所以进行数据属性的复制

4.通过学生的宿舍id查询出宿舍来把宿舍名插入前端的对象中

5.把数据添加到定义的数组当中即可

3.数据的搜索

前端代码:

submitForm(formName) {
    const _this = this
    //让翻页复原
    _this.currentPage = 1
    this.$refs[formName].validate((valid) => {
        if (valid) {
            const _this = this
            _this.ruleForm.page = _this.currentPage
            axios.get('http://localhost:8181/student/search', {params: _this.ruleForm}).then(function (resp) {
                console.log(_this.ruleForm)
                _this.tableData = resp.data.data.data
                _this.total = resp.data.data.total
            })
        }
    });

},

后端代码:

  • controller
@GetMapping("/search")
/*get请求无需在加@RequestBody注解*/
public ResultVo searchStudent(SearchFrom searchFrom) {
    PageVo search = this.studentService.search(searchFrom);
    System.out.println("查询出的数据:" + ResultVoUtil.success(search));
    return ResultVoUtil.success(search);
}
  • service
/*学生页面搜索*/
    @Override
    public PageVo search(SearchFrom searchFrom) {
        /*进行分页操作*/
        Page<Student> StudentSearchPage = new Page<>(searchFrom.getPage(), searchFrom.getSize());
        Page<Student> studentPage = null;
        /*如果搜索框的值为null就选择查询全部*/
        if (searchFrom.getValue().equals("")) {
            studentPage = this.studentMapper.selectPage(StudentSearchPage, null);

        } else {
            /*否则就模糊查询*/
            QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
            /*字段名,值*/
            queryWrapper.like(searchFrom.getKey(), searchFrom.getValue());
            studentPage = this.studentMapper.selectPage(StudentSearchPage, queryWrapper);
        }
        /*因为前端要的是宿舍名,而我们后端查询出来的是宿舍的id所有我们要把他转化一下*/
        List<Student> studentList = studentPage.getRecords();
        //将Vo转换
        List<StudentVo> studentVoList = new ArrayList<>();
        for (Student student : studentList) {
            /*前端需要的实体类*/
            StudentVo studentVo = new StudentVo();
            /*属性的复制 左边为被复制的属性,右边是目标属性*/
            BeanUtils.copyProperties(student, studentVo);
            /*现在根据学生的宿舍id查出宿舍名*/
            Dormitory dormitory = this.dormitoryMapper.selectById(student.getDormitoryId());
            studentVo.setDormitoryName(dormitory.getName());
            studentVoList.add(studentVo);

        }
        PageVo pageVo = new PageVo();
        /*获取总条数*/
        pageVo.setTotal(studentPage.getTotal());
        /*存入查出的数据*/
        System.out.println("查询出的数据:" + studentVoList);
        pageVo.setData(studentVoList);
        return pageVo;
    }

代码功能基本上与前面的学生信息展示基本一直的不在解释

4.学生修改

首先当点击编辑时跳转到编辑页面,通过id查询把数据回填进去

前端代码:

created() {
            const _this = this
            axios.get('http://localhost:8181/dormitory/availableList').then(function (resp) {
                _this.dormitoryList = resp.data.data
            })
            axios.get('http://localhost:8181/student/findById/' + _this.$route.query.id).then(function (resp) {
                _this.ruleForm = resp.data.data
            })
        }

后端代码:

@GetMapping("/findById/{id}")
public ResultVo findByIdStudent(@PathVariable("id") Integer id) {
    /*通过id查询出学生全部信息*/
    Student studentById = this.studentService.getById(id);
    StudentForm studentForm = new StudentForm();
    /*把查询出来的所有学生信息全部复制给studentForm*/
    BeanUtils.copyProperties(studentById, studentForm);
    /*其中老的id就是现在刚查出的id*/
    studentForm.setOldDormitoryId(studentById.getDormitoryId());
    return ResultVoUtil.success(studentForm);
}

上面是回填进去的数据,因为涉及到新宿舍与老宿舍的情况,

所以把查询出来的数据赋值给自定义的对象,其中查询出来的id为该对象的老宿舍id,

下面开始学生修改功能:

前端代码:

 submitForm(formName) {
                const _this = this
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        console.log(_this.ruleForm)
                        axios.put('http://localhost:8181/student/update', _this.ruleForm).then(function (resp) {
                            if (resp.data.code == 0) {
                                _this.$alert(_this.ruleForm.name + '修改成功', '', {
                                    confirmButtonText: '确定',
                                    callback: action => {
                                        _this.$router.push('/studentManager')
                                    }
                                });
                            } else {
                                _this.$alert(_this.ruleForm.name + '修改失败', '', {
                                    confirmButtonText: '确定',
                                    callback: action => {
                                        _this.$router.push('/studentManager')
                                    }
                                });
                            }
                        })
                    }
                });
            },

后端代码:

  • controller
@PutMapping("/update")
public ResultVo updateStudent(@RequestBody StudentForm studentForm) {
    //注意只有get不需要去写@RequestBody
    Boolean update = this.studentService.update(studentForm);
    if (!update) {
        return ResultVoUtil.fail();
    } else {
        return ResultVoUtil.success(null);
    }

}
  • service
/*学生的修改*/
    @Override
    public Boolean update(StudentForm studentForm) {
        //1.更新学生
        Student student = new Student();
        BeanUtils.copyProperties(studentForm, student);
        int updateById = this.studentMapper.updateById(student);
        if (updateById != 1) {
            return false;
        } else {
            /*当提交的新宿舍id与老宿舍id不一直时说明他修改了*/
            if (!studentForm.getDormitoryId().equals(studentForm.getOldDormitoryId())) {
                //老宿舍+1
                try {
                    this.dormitoryMapper.addAvailable(studentForm.getOldDormitoryId());
                    //新宿舍-1
                    this.dormitoryMapper.subAvailable(studentForm.getDormitoryId());
                } catch (Exception e) {
                    return false;
                }

            }
            return true;
        }
    }

上面的studentForm是前端传递过来的其中包括老宿舍id与新宿舍id,我们把数据赋值给student进行跟新,以及后面的宿舍增加减少的情况

5.删除功能

前端代码:

del(row) {
                const _this = this
                this.$confirm('确认删除【' + row.name + '】吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.delete('http://localhost:8181/student/deleteById/' + row.id).then(function (resp) {
                        if (resp.data.code == 0) {
                            _this.$alert('【' + row.name + '】已删除', '', {
                                confirmButtonText: '确定',
                                callback: action => {
                                    location.reload()
                                }
                            });
                        }
                    });
                });
            }

后端代码:

  • controller
  /*学生删除功能*/
    @DeleteMapping("/deleteById/{id}")
    public ResultVo deleteByIdStudent(@PathVariable("id") Integer id) {
        Boolean deleteById = this.studentService.deleteById(id);
        if (!deleteById) {
            return ResultVoUtil.fail();
        } else {
            return ResultVoUtil.success(null);
        }
    }
  • service

    /*删除学生*/
    @Override
    public Boolean deleteById(Integer id) {
        //首先要修改学生的
        /*1.通过学生id查出学生信息*/
        Student student = this.studentMapper.selectById(id);

        try {
            /*2.通过学生的宿舍id去查询他住在几号宿舍*/
            Dormitory dormitory = this.dormitoryMapper.selectById(student.getDormitoryId());
            if (dormitory.getType() > dormitory.getAvailable()) {
                /*根据查询出宿舍,进行人数添加*/
                this.dormitoryMapper.addAvailable(dormitory.getId());
            }
        } catch (Exception e) {
            return false;
        }
        //删除学生数据
        int delete = this.studentMapper.deleteById(id);
        if (delete != 1) {
            return false;
        }
        return true;
    }

逻辑梳理:要删除学生,学生所在的宿舍数量也要加1

1.通过学生id查询出是哪个学生要被删除

2.根据学生的宿舍id查询出宿舍信息

3.通过宿舍id把增加该宿舍的数量

4.以上都成功后删除学生

6、楼宇模块

其实与前面功能基本相似这里制作简单描述

controller

package com.lsa.southwind.controller;


import com.lsa.southwind.entity.Building;
import com.lsa.southwind.form.SearchForm;
import com.lsa.southwind.service.BuildingService;
import com.lsa.southwind.util.ResultVoUtil;
import com.lsa.southwind.vo.PageVo;
import com.lsa.southwind.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author admin
 * @since 2023-02-25
 */
@RestController
@RequestMapping("/building")
public class BuildingController {
    @Autowired
    private BuildingService buildingService;

    @PostMapping("/save")
    public ResultVo save(@RequestBody Building building) {
        boolean save = this.buildingService.save(building);
        if (!save) {
            return ResultVoUtil.fail();
        } else {
            return ResultVoUtil.success(null);
        }

    }

    @GetMapping("/list/{page}/{size}")
    public ResultVo buildinglist(@PathVariable("page") Integer page, @PathVariable("size") Integer size) {
        PageVo buildinglist = this.buildingService.list(page, size);
        return ResultVoUtil.success(buildinglist);
    }

    @GetMapping("/search")
    public ResultVo search(SearchForm searchForm) {
        PageVo searchList = this.buildingService.search(searchForm);
        return ResultVoUtil.success(searchList);
    }

    /*学生修改*/
    /*修改信息回填*/
    @GetMapping("/findById/{id}")
    public ResultVo findById(@PathVariable("id") Integer id) {
        Building buildingone = this.buildingService.getById(id);
        return ResultVoUtil.success(buildingone);
    }

    @PutMapping("/update")
    public ResultVo update(@RequestBody Building building) {
        boolean update = this.buildingService.updateById(building);
        if (!update) {
            return ResultVoUtil.fail();
        } else {
            return ResultVoUtil.success(null);
        }
    }

    @DeleteMapping("/deleteById/{id}")
    public ResultVo deleteById(@PathVariable("id") Integer id) {
        Boolean deleteById = this.buildingService.deleteById(id);
        if (!deleteById) {
            return ResultVoUtil.fail();
        } else {
            return ResultVoUtil.success(null);
        }
    }

    @GetMapping("/list")
    public ResultVo list() {
        List<Building> buildingList = this.buildingService.list();
        return ResultVoUtil.success(buildingList);
    }
}


package com.lsa.southwind.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lsa.southwind.entity.Building;
import com.lsa.southwind.entity.Dormitory;
import com.lsa.southwind.entity.DormitoryAdmin;
import com.lsa.southwind.entity.Student;
import com.lsa.southwind.form.SearchForm;
import com.lsa.southwind.mapper.BuildingMapper;
import com.lsa.southwind.mapper.DormitoryAdminMapper;
import com.lsa.southwind.mapper.DormitoryMapper;
import com.lsa.southwind.mapper.StudentMapper;
import com.lsa.southwind.service.BuildingService;
import com.lsa.southwind.vo.BuildingVo;
import com.lsa.southwind.vo.PageVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author admin
 * @since 2023-02-25
 */
@Service
public class BuildingServiceImpl extends ServiceImpl<BuildingMapper, Building> implements BuildingService {
    @Autowired
    private BuildingMapper buildingMapper;
    @Autowired
    private DormitoryAdminMapper dormitoryAdminMapper;
    @Autowired
    private DormitoryMapper dormitoryMapper;
    @Autowired
    private StudentMapper studentMapper;

    @Override
    public PageVo list(Integer page, Integer size) {
        //1.首先进行分页查询
        Page<Building> buildingPage = new Page<>(page, size);
        Page<Building> buildingList = this.buildingMapper.selectPage(buildingPage, null);

        List<BuildingVo> buildingVoList = new ArrayList<>();
        //2.把分页查询出来的数据进行遍历并赋值给为前端定义的BuildingVo
        for (Building building : buildingList.getRecords()) {
            BuildingVo buildingVo = new BuildingVo();
            BeanUtils.copyProperties(building, buildingVo);
            /*3.因为前端显示的是管理员的名字,而后端保存的是管理员的id,
             所以通过id查询出管理员的姓名并赋值给定义的VO
             */
            //4.通过id查询出所以管理员信息并把姓名赋值给前端
            DormitoryAdmin dormitoryAdmin = this.dormitoryAdminMapper.selectById(building.getAdminId());
            buildingVo.setAdminName(dormitoryAdmin.getName());
            buildingVoList.add(buildingVo);
        }
        PageVo pageVo = new PageVo();
        pageVo.setData(buildingVoList);
        pageVo.setTotal(buildingList.getTotal());
        return pageVo;
    }

    //搜索查询
    @Override
    public PageVo search(SearchForm searchForm) {
        Page<Building> buildingPage = new Page<>(searchForm.getPage(), searchForm.getSize());
        Page<Building> buildingPageList = null;
        if (searchForm.getValue().equals("")) {
            buildingPageList = this.buildingMapper.selectPage(buildingPage, null);
        } else {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.like(searchForm.getKey(), searchForm.getValue());
            buildingPageList = this.buildingMapper.selectPage(buildingPage, queryWrapper);
        }
        List<BuildingVo> buildingVoList = new ArrayList<>();
        for (Building building : buildingPageList.getRecords()) {
            BuildingVo buildingVo = new BuildingVo();
            BeanUtils.copyProperties(building, buildingVo);
            /*通过楼宇宿舍管理员id获取该管理员的名字*/
            DormitoryAdmin dormitoryAdmin = this.dormitoryAdminMapper.selectById(building.getAdminId());
            buildingVo.setAdminName(dormitoryAdmin.getName());
            buildingVoList.add(buildingVo);
        }
        PageVo pageVo = new PageVo();
        pageVo.setData(buildingVoList);
        pageVo.setTotal(buildingPageList.getTotal());
        return pageVo;
    }

    @Override
    public Boolean deleteById(Integer id) {
        //1.找到楼宇中的所有宿舍
        QueryWrapper<Dormitory> dormitoryQueryWrapper = new QueryWrapper<>();
        dormitoryQueryWrapper.eq("building_id", id);
        List<Dormitory> dormitoryList = this.dormitoryMapper.selectList(dormitoryQueryWrapper);
        for (Dormitory dormitory : dormitoryList) {
            //2.找到宿舍中的所有学生
            QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
            studentQueryWrapper.eq("dormitory_id", dormitory.getId());
            List<Student> studentList = this.studentMapper.selectList(studentQueryWrapper);
            for (Student student : studentList) {
                //3.给学生换宿舍
                /*
                 * 查出除了要被删除的宿舍外所有空余宿舍
                 * 然后把要被删除楼里宿舍的学生给他换过去
                 * 更新学生信息
                 * 更新宿舍信息
                 * */
                Integer availableDormitoryId = this.dormitoryMapper.findAvailableDormitoryId(id);
                student.setDormitoryId(availableDormitoryId);
                try {
                    this.studentMapper.updateById(student);
                    this.dormitoryMapper.subAvailable(availableDormitoryId);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            int dormitorydeleteById = this.dormitoryMapper.deleteById(dormitory.getId());
            if (dormitorydeleteById != 1) return false;

        }
        int buildingdelete = this.buildingMapper.deleteById(id);
        if (buildingdelete != 1) return false;

        return true;

    }

}

这里最主要的其实就是删除功能,因为想要

删除一个楼宇首先你查看他当中的宿舍,

通过宿舍id查询出学生信息,给学生找空余宿舍

进行宿舍更改

个人认为这一点不太完美,还有优化的空间

7、宿舍模块

基本代码

controller

package com.lsa.southwind.controller;


import com.lsa.southwind.entity.Dormitory;
import com.lsa.southwind.form.SearchForm;
import com.lsa.southwind.service.DormitoryService;
import com.lsa.southwind.util.ResultVoUtil;
import com.lsa.southwind.vo.PageVo;
import com.lsa.southwind.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author admin
 * @since 2023-02-25
 */
@RestController
@RequestMapping("/dormitory")
public class DormitoryController {
    @Autowired
    private DormitoryService dormitoryService;

    @GetMapping("/availableList")
    public ResultVo availableList() {
        ResultVo availableList = this.dormitoryService.availableList();
        return availableList;
    }

    @PostMapping("/save")
    /*除了get不用其他都要加*/
    public ResultVo save(@RequestBody Dormitory dormitory) {
        dormitory.setAvailable(dormitory.getType());
        boolean save = this.dormitoryService.save(dormitory);
        if (!save) {
            return ResultVoUtil.fail();
        } else {
            return ResultVoUtil.success(null);
        }
    }

    @GetMapping("/list/{page}/{size}")
    public ResultVo listDormitory(@PathVariable("page") Integer page, @PathVariable("size") Integer size) {
        PageVo list = this.dormitoryService.list(page, size);
        return ResultVoUtil.success(list);
    }

    @GetMapping("/search")
    public ResultVo search(SearchForm searchForm) {
        PageVo search = this.dormitoryService.search(searchForm);

        return ResultVoUtil.success(search);
    }

    /*学生修改*/
    @GetMapping("/findById/{id}")
    public ResultVo findById(@PathVariable("id") Integer id) {
        Dormitory dormitory = this.dormitoryService.getById(id);
        return ResultVoUtil.success(dormitory);
    }

    @PutMapping("/update")
    public ResultVo update(@RequestBody Dormitory dormitory) {
        boolean updateById = this.dormitoryService.updateById(dormitory);
        if (!updateById) {
            return ResultVoUtil.fail();
        } else {
            return ResultVoUtil.success(null);
        }
    }

    @DeleteMapping("/deleteById/{id}")
    public ResultVo deleteById(@PathVariable("id") Integer id) {
        Boolean deleteById = this.dormitoryService.deleteById(id);
        if (!deleteById) {
            return ResultVoUtil.fail();
        } else {
            return ResultVoUtil.success(null);
        }
    }
}

serviceImpl

package com.lsa.southwind.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lsa.southwind.entity.Dormitory;
import com.lsa.southwind.entity.Student;
import com.lsa.southwind.form.SearchForm;
import com.lsa.southwind.form.StudentForm;
import com.lsa.southwind.mapper.DormitoryMapper;
import com.lsa.southwind.mapper.StudentMapper;
import com.lsa.southwind.service.StudentService;
import com.lsa.southwind.util.CommonUtil;
import com.lsa.southwind.vo.PageVo;
import com.lsa.southwind.vo.StudentVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author admin
 * @since 2023-02-25
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private DormitoryMapper dormitoryMapper;

    @Override
    public Boolean saveStudent(Student student) {
        //添加成功,修改入住的宿舍的人数数量
        //1.先查看要入住的宿舍的数量,通过学生宿舍id去查询该宿舍的全部信息
        Dormitory dormitory = this.dormitoryMapper.selectById(student.getDormitoryId());
        //2.判断要入住的宿舍的人数
        if (dormitory.getAvailable() == 0) {
            return false;
        } else {
            //3.如果不等于0就进行人数更改
            dormitory.setAvailable(dormitory.getAvailable() - 1);
            int updateById = this.dormitoryMapper.updateById(dormitory);
            if (updateById != 1) {
                return false;
            }
        }
        //4.添加学生
        student.setCreateDate(CommonUtil.createDate());
        student.setState("入住");
        int insert = this.studentMapper.insert(student);
        if (insert != 1) {
            return false;
        } else {
            return true;
        }

    }

    /*学生页面查询*/
    @Override
    public PageVo list(Integer page, Integer size) {
        /*分页查询 page页数,size大小*/
        Page<Student> studentListPage = new Page<>(page, size);
        Page<Student> resultPage = this.studentMapper.selectPage(studentListPage, null);
        /*因为前端要的是宿舍名,而我们后端查询出来的是宿舍的id所有我们要把他转化一下*/
        List<Student> studentList = resultPage.getRecords();
        //将Vo转换
        List<StudentVo> studentVoList = new ArrayList<>();
        for (Student student : studentList) {
            /*前端需要的实体类*/
            StudentVo studentVo = new StudentVo();
            /*属性的复制 左边为被复制的属性,右边是目标属性*/
            BeanUtils.copyProperties(student, studentVo);
            /*现在根据学生的宿舍id查出宿舍名*/
            Dormitory dormitory = this.dormitoryMapper.selectById(student.getDormitoryId());
            studentVo.setDormitoryName(dormitory.getName());
            studentVoList.add(studentVo);

        }
        PageVo pageVo = new PageVo();
        /*获取总条数*/
        pageVo.setTotal(resultPage.getTotal());
        /*存入查出的数据*/
        System.out.println("查询出的数据:" + studentVoList);
        pageVo.setData(studentVoList);
        return pageVo;
    }

    /*学生页面搜索*/
    @Override
    public PageVo search(SearchForm searchForm) {
        /*进行分页操作*/
        Page<Student> StudentSearchPage = new Page<>(searchForm.getPage(), searchForm.getSize());
        Page<Student> studentPage = null;
        /*如果搜索框的值为null就选择查询全部*/
        if (searchForm.getValue().equals("")) {
            studentPage = this.studentMapper.selectPage(StudentSearchPage, null);

        } else {
            /*否则就模糊查询*/
            QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
            /*字段名,值*/
            queryWrapper.like(searchForm.getKey(), searchForm.getValue());
            studentPage = this.studentMapper.selectPage(StudentSearchPage, queryWrapper);
        }
        /*因为前端要的是宿舍名,而我们后端查询出来的是宿舍的id所有我们要把他转化一下*/
        List<Student> studentList = studentPage.getRecords();
        //将Vo转换
        List<StudentVo> studentVoList = new ArrayList<>();
        for (Student student : studentList) {
            /*前端需要的实体类*/
            StudentVo studentVo = new StudentVo();
            /*属性的复制 左边为被复制的属性,右边是目标属性*/
            BeanUtils.copyProperties(student, studentVo);
            /*现在根据学生的宿舍id查出宿舍名*/
            Dormitory dormitory = this.dormitoryMapper.selectById(student.getDormitoryId());
            studentVo.setDormitoryName(dormitory.getName());
            studentVoList.add(studentVo);

        }
        PageVo pageVo = new PageVo();
        /*获取总条数*/
        pageVo.setTotal(studentPage.getTotal());
        /*存入查出的数据*/
        System.out.println("查询出的数据:" + studentVoList);
        pageVo.setData(studentVoList);
        return pageVo;
    }

    /*学生的修改*/
    @Override
    public Boolean update(StudentForm studentForm) {
        //1.更新学生
        Student student = new Student();
        BeanUtils.copyProperties(studentForm, student);
        /*通过新宿舍id查询出全部宿舍信息*/
        Dormitory dormitoryNew = this.dormitoryMapper.selectById(student.getDormitoryId());
        if (dormitoryNew.getAvailable() == 0) {
            return false;
        } else {
            int updateById = this.studentMapper.updateById(student);
            if (updateById != 1) {
                return false;
            } else {
                /*当提交老宿舍id与新的不一样时说明他修改了*/
                if (!studentForm.getDormitoryId().equals(studentForm.getOldDormitoryId())) {
                    //老宿舍+1
                    try {
                        this.dormitoryMapper.addAvailable(studentForm.getOldDormitoryId());
                        //新宿舍-1
                        this.dormitoryMapper.subAvailable(studentForm.getDormitoryId());
                    } catch (Exception e) {
                        return false;
                    }
                }
                return true;
            }
        }
    }

    /*删除学生*/
    @Override
    public Boolean deleteById(Integer id) {
        //首先要修改学生的
        /*1.通过学生id查出学生信息*/
        Student student = this.studentMapper.selectById(id);

        try {
            /*2.通过学生的宿舍id去查询他住在几号宿舍*/
            Dormitory dormitory = this.dormitoryMapper.selectById(student.getDormitoryId());
            if (dormitory.getType() > dormitory.getAvailable()) {
                /*根据查询出宿舍,进行人数添加*/
                this.dormitoryMapper.addAvailable(dormitory.getId());
            }
        } catch (Exception e) {
            return false;
        }
        //删除学生数据
        int delete = this.studentMapper.deleteById(id);
        if (delete != 1) {
            return false;
        }
        return true;
    }


}

8、学生迁出登记

controller

package com.lsa.southwind.controller;


import com.lsa.southwind.form.SearchForm;
import com.lsa.southwind.service.MoveoutService;
import com.lsa.southwind.util.ResultVoUtil;
import com.lsa.southwind.vo.PageVo;
import com.lsa.southwind.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author admin
 * @since 2023-02-25
 */
@RestController
@RequestMapping("/moveout")
public class MoveoutController {
    @Autowired
    private MoveoutService moveoutService;

    @GetMapping("/list/{page}/{size}")
    public ResultVo list(@PathVariable Integer page, @PathVariable Integer size) {
        PageVo list = this.moveoutService.list(page, size);
        return ResultVoUtil.success(list);
    }

    /*模糊查询*/
    @GetMapping("/search")
    public ResultVo search(SearchForm searchForm) {
        PageVo search = this.moveoutService.search(searchForm);

        return ResultVoUtil.success(search);
    }

    @PutMapping("/moveout/{id}/{reason}")
    public ResultVo moveout(@PathVariable("id") Integer id, @PathVariable("reason") String reason) {
        Boolean moveout = this.moveoutService.moveout(id, reason);
        if (!moveout) return ResultVoUtil.fail();
        return ResultVoUtil.success(null);
    }

    /*学生迁出列表*/
    @GetMapping("/moveoutList/{page}/{size}")
    public ResultVo moveoutList(@PathVariable("page") Integer page, @PathVariable("size") Integer size) {
        PageVo moveoutList = this.moveoutService.moveoutList(page, size);

        return ResultVoUtil.success(moveoutList);
    }

    @GetMapping("/moveoutSearch")
    public ResultVo moveoutSearch(SearchForm searchForm) {
        PageVo pageVo = this.moveoutService.moveoutSearch(searchForm);
        return ResultVoUtil.success(pageVo);
    }
}


serviceImpl

package com.lsa.southwind.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lsa.southwind.entity.Dormitory;
import com.lsa.southwind.entity.Moveout;
import com.lsa.southwind.entity.Student;
import com.lsa.southwind.form.SearchForm;
import com.lsa.southwind.mapper.DormitoryMapper;
import com.lsa.southwind.mapper.MoveoutMapper;
import com.lsa.southwind.mapper.StudentMapper;
import com.lsa.southwind.service.MoveoutService;
import com.lsa.southwind.util.CommonUtil;
import com.lsa.southwind.vo.MoveoutVo;
import com.lsa.southwind.vo.PageVo;
import com.lsa.southwind.vo.StudentVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author admin
 * @since 2023-02-25
 */
@Service
public class MoveoutServiceImpl extends ServiceImpl<MoveoutMapper, Moveout> implements MoveoutService {
    @Autowired
    private MoveoutMapper moveoutMapper;

    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private DormitoryMapper dormitoryMapper;

    @Override
    public PageVo list(Integer page, Integer size) {
        Page<Student> studentPage = new Page<>(page, size);
        QueryWrapper<Student> studentqueryWrapper = new QueryWrapper<>();
        studentqueryWrapper.eq("state", "入住");
        Page<Student> resultPage = this.studentMapper.selectPage(studentPage, studentqueryWrapper);
        List<Student> studentList = resultPage.getRecords();
        //VO转换
        List<StudentVo> studentVOList = new ArrayList<>();
        for (Student student : studentList) {
            StudentVo StudentVo = new StudentVo();
            BeanUtils.copyProperties(student, StudentVo);
            Dormitory dormitory = this.dormitoryMapper.selectById(student.getDormitoryId());
            StudentVo.setDormitoryName(dormitory.getName());
            studentVOList.add(StudentVo);
        }
        PageVo pageVo = new PageVo();
        pageVo.setData(studentVOList);
        pageVo.setTotal(resultPage.getTotal());
        return pageVo;
    }

    @Override
    public PageVo search(SearchForm searchForm) {
        /*进行分页操作*/
        Page<Student> StudentSearchPage = new Page<>(searchForm.getPage(), searchForm.getSize());
        Page<Student> studentPage = null;
        QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
        studentQueryWrapper.eq("state", "入住");
        /*如果搜索框的值为null就选择查询全部*/
        if (searchForm.getValue().equals("")) {
            studentPage = this.studentMapper.selectPage(StudentSearchPage, studentQueryWrapper);

        } else {
            /*否则就模糊查询*/
            QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
            /*字段名,值*/
            queryWrapper.like(searchForm.getKey(), searchForm.getValue());
            studentPage = this.studentMapper.selectPage(StudentSearchPage, queryWrapper);
        }
        /*因为前端要的是宿舍名,而我们后端查询出来的是宿舍的id所有我们要把他转化一下*/
        List<Student> studentList = studentPage.getRecords();
        //将Vo转换
        List<StudentVo> studentVoList = new ArrayList<>();
        for (Student student : studentList) {
            /*前端需要的实体类*/
            StudentVo studentVo = new StudentVo();
            /*属性的复制 左边为被复制的属性,右边是目标属性*/
            BeanUtils.copyProperties(student, studentVo);
            /*现在根据学生的宿舍id查出宿舍名*/
            Dormitory dormitory = this.dormitoryMapper.selectById(student.getDormitoryId());
            studentVo.setDormitoryName(dormitory.getName());
            studentVoList.add(studentVo);

        }
        PageVo pageVo = new PageVo();
        /*获取总条数*/
        pageVo.setTotal(studentPage.getTotal());
        /*存入查出的数据*/
        pageVo.setData(studentVoList);
        return pageVo;
    }

    @Override
    public Boolean moveout(Integer id, String reason) {
        Moveout moveout = new Moveout();
        Student student = this.studentMapper.selectById(id);
        moveout.setStudentId(student.getId());
        moveout.setDormitoryId(student.getDormitoryId());
        moveout.setReason(reason);
        moveout.setCreateDate(CommonUtil.createDate());
        //插入迁出信息
        int moveoutinsert = this.moveoutMapper.insert(moveout);
        if (moveoutinsert != 1) return false;
        //更新学生信息
        student.setState("迁出");
        int studentupdateById = this.studentMapper.updateById(student);
        if (studentupdateById != 1) return false;

        try {
            /*因为学生迁出了所有,他所住的宿舍数量+1*/
            this.dormitoryMapper.addAvailable(student.getDormitoryId());
        } catch (Exception e) {
            return false;
        }
        return true;
    }

   

  
}


其实主要复杂点的就是模糊查询,因为涉及到了多表查询,

其实这个地方也不是很完美,后期做代码优化

9、学生迁出记录

controller

 /*学生迁出列表*/
    @GetMapping("/moveoutList/{page}/{size}")
    public ResultVo moveoutList(@PathVariable("page") Integer page, @PathVariable("size") Integer size) {
        PageVo moveoutList = this.moveoutService.moveoutList(page, size);

        return ResultVoUtil.success(moveoutList);
    }

    @GetMapping("/moveoutSearch")
    public ResultVo moveoutSearch(SearchForm searchForm) {
        PageVo pageVo = this.moveoutService.moveoutSearch(searchForm);
        return ResultVoUtil.success(pageVo);
    }

serviceImpl

 /*学生迁出记录*/
    @Override
    public PageVo moveoutList(Integer page, Integer size) {
        Page<Moveout> moveoutPage = new Page<>(page, size);
        Page<Moveout> moveoutPageList = this.moveoutMapper.selectPage(moveoutPage, null);
        List<Moveout> moveoutPageListRecords = moveoutPageList.getRecords();
        List<MoveoutVo> moveoutVoList = new ArrayList<>();
        for (Moveout moveout : moveoutPageListRecords) {
            MoveoutVo moveoutVo = new MoveoutVo();
            BeanUtils.copyProperties(moveout, moveoutVo);
            Student student = this.studentMapper.selectById(moveout.getStudentId());
            moveoutVo.setStudentName(student.getName());
            Dormitory dormitory = this.dormitoryMapper.selectById(moveout.getDormitoryId());
            moveoutVo.setDormitoryName(dormitory.getName());
            moveoutVoList.add(moveoutVo);
        }
        PageVo pageVo = new PageVo();
        pageVo.setData(moveoutVoList);
        pageVo.setTotal(moveoutPageList.getTotal());
        return pageVo;
    }

    @Override
    public PageVo moveoutSearch(SearchForm searchForm) {
        Page<Moveout> moveoutPage = new Page<>(searchForm.getPage(), searchForm.getSize());
        Page<Moveout> moveoutPageList = null;
        if (searchForm.getValue().equals("")) {
            moveoutPageList = this.moveoutMapper.selectPage(moveoutPage, null);
        } else {
            QueryWrapper<Moveout> queryWrapper = new QueryWrapper<>();
            if (searchForm.getKey().equals("studentName")) {
                List<Student> studentList = this.studentMapper.moveoutStudentLike(searchForm.getValue());
                List<Integer> idList = new ArrayList<>();
                for (Student student : studentList) {
                    idList.add(student.getId());
                }
                queryWrapper.in("student_id", idList);

            } else if (searchForm.getKey().equals("dormitoryName")) {
                QueryWrapper<Dormitory> dormitoryQueryWrapper = new QueryWrapper<>();
                dormitoryQueryWrapper.like("name", searchForm.getValue());
                List<Dormitory> dormitoryList = this.dormitoryMapper.selectList(dormitoryQueryWrapper);
                List<Integer> idList = new ArrayList<>();
                for (Dormitory dormitory : dormitoryList) {
                    idList.add(dormitory.getId());
                }
                queryWrapper.in("dormitory_id", idList);
            }
            moveoutPageList = this.moveoutMapper.selectPage(moveoutPage, queryWrapper);
        }
        List<MoveoutVo> moveoutVoList = new ArrayList<>();
        for (Moveout moveout : moveoutPageList.getRecords()) {
            MoveoutVo moveoutVo = new MoveoutVo();
            BeanUtils.copyProperties(moveout, moveoutVo);
            Student student = this.studentMapper.selectById(moveout.getStudentId());
            Dormitory dormitory = this.dormitoryMapper.selectById(moveout.getDormitoryId());
            moveoutVo.setStudentName(student.getName());
            moveoutVo.setDormitoryName(dormitory.getName());
            moveoutVoList.add(moveoutVo);
        }
        PageVo pageVo = new PageVo();
        pageVo.setTotal(moveoutPageList.getTotal());
        pageVo.setData(moveoutVoList);
        return pageVo;
    }

10、学生缺勤记录

controller

package com.lsa.southwind.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lsa.southwind.entity.Absent;
import com.lsa.southwind.entity.Building;
import com.lsa.southwind.entity.Dormitory;
import com.lsa.southwind.entity.Student;
import com.lsa.southwind.form.SearchForm;
import com.lsa.southwind.service.AbsentService;
import com.lsa.southwind.service.BuildingService;
import com.lsa.southwind.service.DormitoryService;
import com.lsa.southwind.service.StudentService;
import com.lsa.southwind.util.ResultVoUtil;
import com.lsa.southwind.vo.PageVo;
import com.lsa.southwind.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author admin
 * @since 2023-02-25
 */
@RestController
@RequestMapping("/absent")
public class AbsentController {
    @Autowired
    private AbsentService absentService;
    @Autowired
    private BuildingService buildingService;
    @Autowired
    private DormitoryService dormitoryService;
    @Autowired
    private StudentService studentService;

    @GetMapping("/list/{page}/{size}")
    private ResultVo list(@PathVariable Integer page, @PathVariable Integer size) {
        PageVo list = this.absentService.list(page, size);
        return ResultVoUtil.success(list);
    }

    @GetMapping("/search")
    public ResultVo search(SearchForm searchForm) {
        return ResultVoUtil.success(this.absentService.search(searchForm));
    }


}


serviceImpl

package com.lsa.southwind.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lsa.southwind.entity.*;
import com.lsa.southwind.form.SearchForm;
import com.lsa.southwind.mapper.*;
import com.lsa.southwind.service.AbsentService;
import com.lsa.southwind.vo.AbsentVo;
import com.lsa.southwind.vo.PageVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author admin
 * @since 2023-02-25
 */
@Service
public class AbsentServiceImpl extends ServiceImpl<AbsentMapper, Absent> implements AbsentService {
    @Autowired
    private AbsentMapper absentMapper;
    @Autowired
    private BuildingMapper buildingMapper;
    @Autowired
    private DormitoryMapper dormitoryMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private DormitoryAdminMapper dormitoryAdminMapper;

    @Override
    public PageVo list(Integer page, Integer size) {
        Page<Absent> absentPage = new Page<>(page, size);
        Page<Absent> absentselectPage = this.absentMapper.selectPage(absentPage, null);
        List<AbsentVo> absentVoList = new ArrayList<>();
        for (Absent absent : absentselectPage.getRecords()) {
            AbsentVo absentVo = new AbsentVo();
            BeanUtils.copyProperties(absent, absentVo);
            Building building = this.buildingMapper.selectById(absent.getBuildingId());
            Dormitory dormitory = this.dormitoryMapper.selectById(absent.getDormitoryId());
            Student student = this.studentMapper.selectById(absent.getStudentId());
            DormitoryAdmin dormitoryAdmin = this.dormitoryAdminMapper.selectById(absent.getDormitoryAdminId());
            absentVo.setBuildingName(building.getName());
            absentVo.setDormitoryName(dormitory.getName());
            absentVo.setStudentName(student.getName());
            absentVo.setDormitoryAdminName(dormitoryAdmin.getName());
            absentVoList.add(absentVo);
        }
        PageVo pageVo = new PageVo();
        pageVo.setData(absentVoList);
        pageVo.setTotal(absentselectPage.getTotal());
        return pageVo;
    }

    @Override
    public PageVo search(SearchForm searchForm) {
        Page<Absent> absentPage = new Page<>(searchForm.getPage(), searchForm.getSize());
        Page<Absent> resultPage = null;
        if (searchForm.getValue().equals("")) {
            resultPage = this.absentMapper.selectPage(absentPage, null);
        } else {
            QueryWrapper<Absent> queryWrapper = new QueryWrapper<>();
            if (searchForm.getKey().equals("buildingName")) {
                QueryWrapper<Building> buildingQueryWrapper = new QueryWrapper<>();
                buildingQueryWrapper.like("name", searchForm.getValue());
                List<Building> buildingList = this.buildingMapper.selectList(buildingQueryWrapper);
                List<Integer> idList = new ArrayList<>();
                for (Building building : buildingList) {
                    idList.add(building.getId());
                }
                queryWrapper.in("building_id", idList);
            } else if (searchForm.getKey().equals("dormitoryName")) {
                QueryWrapper<Dormitory> dormitoryQueryWrapper = new QueryWrapper<>();
                dormitoryQueryWrapper.like("name", searchForm.getValue());
                List<Dormitory> dormitoryList = this.dormitoryMapper.selectList(dormitoryQueryWrapper);
                List<Integer> idList = new ArrayList<>();
                for (Dormitory dormitory : dormitoryList) {
                    idList.add(dormitory.getId());
                }
                queryWrapper.in("dormitory_id", idList);
            }
            resultPage = this.absentMapper.selectPage(absentPage, queryWrapper);
        }
        List<AbsentVo> absentVoList = new ArrayList<>();
        for (Absent absent : resultPage.getRecords()) {
            AbsentVo absentVo = new AbsentVo();
            BeanUtils.copyProperties(absent, absentVo);
            absentVo.setBuildingName(this.buildingMapper.selectById(absent.getBuildingId()).getName());
            absentVo.setDormitoryName(this.dormitoryMapper.selectById(absent.getDormitoryId()).getName());
            absentVo.setStudentName(this.studentMapper.selectById(absent.getStudentId()).getName());
            absentVo.setDormitoryAdminName(this.dormitoryAdminMapper.selectById(absent.getDormitoryAdminId()).getName());
            absentVoList.add(absentVo);
        }
        PageVo pageVo = new PageVo();
        pageVo.setTotal(resultPage.getTotal());
        pageVo.setData(absentVoList);
        return pageVo;
    }
}


这个模糊查询与学生迁出记录的模糊查询一样都不是很完美,有点繁琐,后期优化

11、学生缺勤记录登记

controller

  @GetMapping("/buildingList")
    public ResultVo buildingList() {
        List<Building> list = this.buildingService.list();
        return ResultVoUtil.success(list);

    }

    @GetMapping("/findDormitoryByBuildingId/{id}")
    public ResultVo findDormitoryByBuildingId(@PathVariable Integer id) {
        QueryWrapper<Dormitory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("building_id", id);
        List<Dormitory> dormitoryList = this.dormitoryService.list(queryWrapper);
        return ResultVoUtil.success(dormitoryList);
    }

    @GetMapping("/findStudentByDormitoryId/{id}")
    public ResultVo findStudentByDormitoryId(@PathVariable Integer id) {
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dormitory_id", id);
        List<Student> studentList = this.studentService.list(queryWrapper);
        return ResultVoUtil.success(studentList);
    }

    @PostMapping("/save")
    public ResultVo save(@RequestBody Absent absent) {
        String createDate = absent.getCreateDate();
        createDate = createDate.substring(0, 10);
        absent.setCreateDate(createDate);
        boolean save = this.absentService.save(absent);
        if (!save) {
            return ResultVoUtil.fail();
        }
        return ResultVoUtil.success(null);
    }

至此全部的代码也算是编写完成了,一个简单的练手项目,逻辑不难,新手拿来练手用

代码地址:

前端VUE:https://gitee.com/zck0920/my-dormitory-vue

后端springboot:https://gitee.com/zck0920/my-dormitory-springboot

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值