Spring Boot + MySQL 快速搭建管理系统,不能太容易了。。(下)

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介: Spring Boot + MySQL 快速搭建管理系统,不能太容易了。。(下)

4 代码实现

4.1 前台页面

首页面,就是上边看到的那个帅气的首页!

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
    <meta charset="UTF-8">
    <title>xx-manager</title>
</head>
<body>
<header th:replace="xx-header.html"></header>
<div class="container my-2">
    <a th:href="@{/newEmployee}" class="btn btn-primary btn-sm mb-3"> 新增 </a>
    <table border="1" class = "table table-striped table-responsive-md">
        <thead>
        <tr>
            <th>姓名</th>
            <th>邮箱</th>
            <th>电话</th>
            <th>地址</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="employee : ${employees}">
            <td th:text="${employee.name}"></td>
            <td th:text="${employee.email}"></td>
            <td th:text="${employee.mobile}"></td>
            <td th:text="${employee.location}"></td>
            <td><a th:href="@{/updateEmployee/{id}(id=${employee.id})}" class="btn btn-primary">修改</a>
                <a th:href="@{/deleteEmployee/{id}(id=${employee.id})}" class="btn btn-danger">删除</a></td>
        </tr>
        </tbody>
    </table>
    <div th:if="${totalPages > 1}">
        <div class="row col-sm-10">
            <div class="col-sm-2">
                总人数: [[${items}]]
            </div>
            <div class="col-sm-1">
                    <span th:each="i: ${#numbers.sequence(1, totalPages)}">
      <a th:if="${currentPage != i}" th:href="@{'/page/' + ${i}}">[[${i}]]</a>
      <span th:unless="${currentPage != i}">[[${i}]]</span> &nbsp; &nbsp;
                    </span>
            </div>
            <div class="col-sm-1">
                <a th:if="${currentPage < totalPages}" th:href="@{'/page/' + ${currentPage + 1}}">下一页</a>
                <span th:unless="${currentPage < totalPages}">下一页</span>
            </div>
            <div class="col-sm-1">
                <a th:if="${currentPage < totalPages}" th:href="@{'/page/' + ${totalPages}}">尾页</a>
                <span th:unless="${currentPage < totalPages}">尾页</span>
            </div>
        </div>
    </div>
</div>
<footer th:replace="footer.html"></footer>
</body>
</html>

新增功能页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
    <meta charset="UTF-8">
    <title>xx-manager</title>
</head>
<body>
<header th:replace="xx-header.html"></header>
<div class="container">
    <h1>xx-manager</h1>
    <hr>
    <h2>保存</h2>
    <form action="#" th:action="@{/saveEmployee}" th:object="${employee}" method="POST">
        <input type="text" th:field="*{name}" placeholder="姓名" class="form-control mb-4 col-4">
        <input type="text" th:field="*{email}" placeholder="邮箱" class="form-control mb-4 col-4">
        <input type="text" th:field="*{mobile}" placeholder="电话" class="form-control mb-4 col-4">
        <input type="text" th:field="*{location}" placeholder="住址" class="form-control mb-4 col-4">
        <button type="submit" class="btn btn-info col-2">保存</button>
    </form>
    <hr>
    <a th:href="@{/}">回退</a>
</div>
<footer th:replace="footer.html"></footer>
</body>
</html>

修改功能页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
    <meta charset="UTF-8">
    <title>xx-manager</title>
</head>
<body>
<header th:replace="xx-header.html"></header>
<div class="container">
    <h1>xx-manager</h1>
    <hr>
    <h2>更新</h2>
    <form action="#" th:action="@{/saveEmployee}" th:object="${employee}" method="POST">
        <input type="hidden" th:field="*{id}" />
        <input type="text" th:field="*{name}" class="form-control mb-4 col-4">
        <input type="text" th:field="*{email}" class="form-control mb-4 col-4">
        <input type="text" th:field="*{mobile}" class="form-control mb-4 col-4">
        <input type="text" th:field="*{location}" class="form-control mb-4 col-4">
        <button type="submit" class="btn btn-info col-2">修改</button>
    </form>
    <hr>
    <a th:href="@{/}">回退</a>
</div>
<footer th:replace="footer.html"></footer>
</body>
</html>

4.2 后台业务实现

4.2.1 实体类Employee

对应数据库中的表

package com.lbh.xxmanager.entity;
import javax.persistence.*;
/**
 * Copyright(c)lbhbinhao@163.com
 * @author liubinhao
 * @date 2021/1/7
 * ++++ ______                           ______             ______
 * +++/     /|                         /     /|           /     /|
 * +/_____/  |                       /_____/  |         /_____/  |
 * |     |   |                      |     |   |        |     |   |
 * |     |   |                      |     |   |________|     |   |
 * |     |   |                      |     |  /         |     |   |
 * |     |   |                      |     |/___________|     |   |
 * |     |   |___________________   |     |____________|     |   |
 * |     |  /                  / |  |     |   |        |     |   |
 * |     |/ _________________/  /   |     |  /         |     |  /
 * |_________________________|/b    |_____|/           |_____|/
 */
@Entity
@Table(name = "xx_employee")
public class Employee {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    @Column(name = "name")
    private String name;
    @Column(name = "email")
    private String email;
    @Column(name = "mobile")
    private String mobile;
    @Column(name = "location")
    private String location;
    @Column(name="status")
    private int status;
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getMobile() {
        return mobile;
    }
    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
    public String getLocation() {
        return location;
    }
    public void setLocation(String location) {
        this.location = location;
    }
    public int getStatus() {
        return status;
    }
    public void setStatus(int status) {
        this.status = status;
    }
}

4.2.2 数据库操作层repo

package com.lbh.xxmanager.repo;
import com.lbh.xxmanager.entity.Employee;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
 * Copyright(c)lbhbinhao@163.com
 * @author liubinhao
 * @date 2021/1/7
 * ++++ ______                           ______             ______
 * +++/     /|                         /     /|           /     /|
 * +/_____/  |                       /_____/  |         /_____/  |
 * |     |   |                      |     |   |        |     |   |
 * |     |   |                      |     |   |________|     |   |
 * |     |   |                      |     |  /         |     |   |
 * |     |   |                      |     |/___________|     |   |
 * |     |   |___________________   |     |____________|     |   |
 * |     |  /                  / |  |     |   |        |     |   |
 * |     |/ _________________/  /   |     |  /         |     |  /
 * |_________________________|/b    |_____|/           |_____|/
 */
@Repository
public interface EmployeeRepository extends JpaRepository<Employee,Long> {
    List<Employee> findAllByStatus(int status);
    Page<Employee> findAllByStatus(int status, Pageable pageable);
    Page<Employee> findAllByStatusAndLocationLikeOrNameLikeOrEmailLike(int status,String locaion,String name,String email, Pageable pageable);
}

4.2.3 业务代码service

接口:

package com.lbh.xxmanager.service;
import com.lbh.xxmanager.entity.Employee;
import org.springframework.data.domain.Page;
import java.util.List;
/**
 * Copyright(c)lbhbinhao@163.com
 * @author liubinhao
 * @date 2021/1/7
 * ++++ ______                           ______             ______
 * +++/     /|                         /     /|           /     /|
 * +/_____/  |                       /_____/  |         /_____/  |
 * |     |   |                      |     |   |        |     |   |
 * |     |   |                      |     |   |________|     |   |
 * |     |   |                      |     |  /         |     |   |
 * |     |   |                      |     |/___________|     |   |
 * |     |   |___________________   |     |____________|     |   |
 * |     |  /                  / |  |     |   |        |     |   |
 * |     |/ _________________/  /   |     |  /         |     |  /
 * |_________________________|/b    |_____|/           |_____|/
 */
public interface EmployeeService {
    List<Employee> findAllEmployees();
    void saveEmployee(Employee employee);
    Employee getEmployeeById(long id);
    void deleteEmployeeById(long id);
    Page<Employee> findPaging(int no,int size);
    Page<Employee> findPaging(int no,int size,String searchKey);
}

业务实现类:

package com.lbh.xxmanager.service;
import com.lbh.xxmanager.entity.Employee;
import com.lbh.xxmanager.repo.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
/**
 * Copyright(c)lbhbinhao@163.com
 *
 * @author liubinhao
 * @date 2021/1/7
 * ++++ ______                           ______             ______
 * +++/     /|                         /     /|           /     /|
 * +/_____/  |                       /_____/  |         /_____/  |
 * |     |   |                      |     |   |        |     |   |
 * |     |   |                      |     |   |________|     |   |
 * |     |   |                      |     |  /         |     |   |
 * |     |   |                      |     |/___________|     |   |
 * |     |   |___________________   |     |____________|     |   |
 * |     |  /                  / |  |     |   |        |     |   |
 * |     |/ _________________/  /   |     |  /         |     |  /
 * |_________________________|/b    |_____|/           |_____|/
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeRepository employeeRepository;
    @Override
    public List<Employee> findAllEmployees() {
        return employeeRepository.findAllByStatus(0);
    }
    @Override
    public void saveEmployee(Employee employee) {
        employee.setStatus(0);
        employeeRepository.save(employee);
    }
    @Override
    public Employee getEmployeeById(long id) {
        Optional<Employee> byId = employeeRepository.findById(id);
        Employee employee = null;
        if (byId.isPresent()){
            employee = byId.get();
        }else {
            throw new RuntimeException("该id员工不存在!");
        }
        return employee;
    }
    @Override
    public void deleteEmployeeById(long id) {
        Employee employeeById = getEmployeeById(id);
        employeeById.setStatus(1);
        employeeRepository.save(employeeById);
    }
    @Override
    public Page<Employee> findPaging(int no, int size) {
        Pageable pageable = PageRequest.of(no - 1,size);
        return employeeRepository.findAllByStatus(0,pageable);
    }
    @Override
    public Page<Employee> findPaging(int no, int size, String searchKey) {
        String key = "%"+searchKey+"%";
        Pageable pageable = PageRequest.of(no - 1,size);
        return employeeRepository.findAllByStatusAndLocationLikeOrNameLikeOrEmailLike(0,key,key,key,pageable);
    }
}

4.2.4 Web接口

package com.lbh.xxmanager.controller;
import com.lbh.xxmanager.entity.Employee;
import com.lbh.xxmanager.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;
import java.util.List;
/**
 * Copyright(c)lbhbinhao@163.com
 * @author liubinhao
 * @date 2021/1/7
 * ++++ ______                           ______             ______
 * +++/     /|                         /     /|           /     /|
 * +/_____/  |                       /_____/  |         /_____/  |
 * |     |   |                      |     |   |        |     |   |
 * |     |   |                      |     |   |________|     |   |
 * |     |   |                      |     |  /         |     |   |
 * |     |   |                      |     |/___________|     |   |
 * |     |   |___________________   |     |____________|     |   |
 * |     |  /                  / |  |     |   |        |     |   |
 * |     |/ _________________/  /   |     |  /         |     |  /
 * |_________________________|/b    |_____|/           |_____|/
 */
@Controller
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    @GetMapping("/")
    public String index(Model model){
        model.addAttribute("employees",employeeService.findAllEmployees());
        return "redirect:/page/1";
    }
    @GetMapping("/newEmployee")
    public String newEmployee(Model model){
        Employee employee = new Employee();
        model.addAttribute("employee",employee);
        return "new_employee";
    }
    @PostMapping("/saveEmployee")
    public String saveEmployee(@ModelAttribute Employee employee){
        employeeService.saveEmployee(employee);
        return "redirect:/";
    }
    @GetMapping("/updateEmployee/{id}")
    public String updateEmployee(@PathVariable Long id,Model model){
        Employee employeeById = employeeService.getEmployeeById(id);
        model.addAttribute("employee",employeeById);
        return "update_employee";
    }
    @GetMapping("/deleteEmployee/{id}")
    public String deleteEmployee(@PathVariable Long id){
        employeeService.deleteEmployeeById(id);
        return "redirect:/";
    }
    @GetMapping("/page/{pageNo}")
    public String findPaging(@PathVariable int pageNo, @RequestParam(required = false) String key, Model model){
        Page<Employee> paging = null;
        if (StringUtils.isEmpty(key)) {
            paging = employeeService.findPaging(pageNo, 5);
        }
        else{
            paging = employeeService.findPaging(pageNo, 5,key);
        }
        List<Employee> content = paging.getContent();
        model.addAttribute("currentPage",pageNo);
        model.addAttribute("totalPages",paging.getTotalPages());
        model.addAttribute("items",paging.getTotalElements());
        model.addAttribute("employees",content);
        return "index";
    }
}

4.3 配置文件

springboot的配置文件

server.port=9001
spring.datasource.username=root
spring.datasource.password=你的数据库密码
spring.datasource.url=jdbc:mysql://localhost:3303/xx-manager?serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=CONVERT_TO_NULL&autoReconnect=true&useSSL=false&failOverReadOnly=false
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
# update 这样写可以自动建表,更新表
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto=update
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type=TRACE

5 总结

写一个这样简单的后台信息管理还是不难,看来笔者还是宝刀未老。下班回家开始做,不过写博客是真滴难,都过了12点还没有写

完,写博客和我写代码的时间也相差无几了。哎,我这可怜的头发啊。

image.png

相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
5天前
|
Web App开发 编解码 Java
B/S基层卫生健康云HIS医院管理系统源码 SaaS模式 、Springboot框架
基层卫生健康云HIS系统采用云端SaaS服务的方式提供,使用用户通过浏览器即能访问,无需关注系统的部署、维护、升级等问题,系统充分考虑了模板化、配置化、智能化、扩展化等设计方法,覆盖了基层医疗机构的主要工作流程,能够与监管系统有序对接,并能满足未来系统扩展的需要。
33 4
|
23天前
|
存储 关系型数据库 MySQL
轻松入门MySQL:数据库设计之范式规范,优化企业管理系统效率(21)
轻松入门MySQL:数据库设计之范式规范,优化企业管理系统效率(21)
|
23天前
|
SQL 关系型数据库 MySQL
轻松入门MySQL:保障数据完整性,MySQL事务在进销存管理系统中的应用(12)
轻松入门MySQL:保障数据完整性,MySQL事务在进销存管理系统中的应用(12)
|
25天前
|
存储 Java 关系型数据库
实验室设备管理系统【GUI/Swing+MySQL】(Java课设)
实验室设备管理系统【GUI/Swing+MySQL】(Java课设)
17 0
|
1天前
|
SQL 关系型数据库 MySQL
Spring_jdbc数据连接池(mysql实现增、删、改、查)
Spring_jdbc数据连接池(mysql实现增、删、改、查)
7 0
|
7天前
|
小程序 JavaScript Java
基于SpringBoot+Vue+uniapp微信小程序的教师管理系统的详细设计和实现
基于SpringBoot+Vue+uniapp微信小程序的教师管理系统的详细设计和实现
34 2
|
7天前
|
小程序 JavaScript Java
基于SpringBoot+Vue+uniapp微信小程序的健身管理系统及会员微信小程序的详细设计和实现
基于SpringBoot+Vue+uniapp微信小程序的健身管理系统及会员微信小程序的详细设计和实现
25 0
|
8天前
|
Java 关系型数据库 MySQL
一套java+ spring boot与vue+ mysql技术开发的UWB高精度工厂人员定位全套系统源码有应用案例
UWB (ULTRA WIDE BAND, UWB) 技术是一种无线载波通讯技术,它不采用正弦载波,而是利用纳秒级的非正弦波窄脉冲传输数据,因此其所占的频谱范围很宽。一套UWB精确定位系统,最高定位精度可达10cm,具有高精度,高动态,高容量,低功耗的应用。
一套java+ spring boot与vue+ mysql技术开发的UWB高精度工厂人员定位全套系统源码有应用案例
|
16天前
|
JavaScript 前端开发 Java
Springboot+vue地方废品回收机构管理系统
Spring Boot和Vue.js结合打造Web应用。Spring Boot简化企业级应用开发,Vue.js专注用户界面。示例展示了一个简单的废品回收系统,包含用户管理、废品分类和回收记录模块。后端提供获取废品分类的API,前端使用Vue.js和Axios展示分类列表。实际项目需扩展登录、权限等更多功能。
23 7
|
16天前
|
前端开发 JavaScript Java
Springboot+vue的医患档案管理系统
这是一个医患档案管理系统,包含用户管理、病历管理和预约管理模块。示例展示了一个Spring Boot后端接口,用于获取所有病历信息,以及一个Vue.js前端,使用Axios调用该接口显示病历列表。实际项目需考虑登录、权限及病历CRUD功能,可按需求和技术栈扩展。
26 7