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

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS PostgreSQL,集群系列 2核4GB
云数据库 RDS MySQL,高可用系列 2核4GB
简介: 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

相关实践学习
如何快速连接云数据库RDS MySQL
本场景介绍如何通过阿里云数据管理服务DMS快速连接云数据库RDS MySQL,然后进行数据表的CRUD操作。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
1月前
|
消息中间件 缓存 弹性计算
纯PHP+MySQL手搓高性能论坛系统!代码精简,拒绝臃肿
本内容分享了一套经实战验证的社交系统架构设计,支撑从1到100万用户的发展,并历经6次流量洪峰考验。架构涵盖客户端层(App、小程序、公众号)、接入层(API网关、负载均衡、CDN)、业务服务层(用户、内容、关系、消息等服务)、数据层(MySQL、Redis、MongoDB等)及运维监控层(日志、监控、告警)。核心设计包括数据库分库分表、多级缓存体系、消息队列削峰填谷、CQRS模式与热点数据动态缓存。同时提供应对流量洪峰的弹性伸缩方案及降级熔断机制,并通过Prometheus实现全链路监控。开源建议结构清晰,适合大型社交平台构建与优化。
128 11
|
1月前
|
关系型数据库 MySQL Linux
CentOS 7系统下详细安装MySQL 5.7的步骤:包括密码配置、字符集配置、远程连接配置
以上就是在CentOS 7系统下安装MySQL 5.7的详细步骤。希望这个指南能帮助你顺利完成安装。
270 26
|
28天前
|
监控 Java 关系型数据库
Spring Boot整合MySQL主从集群同步延迟解决方案
本文针对电商系统在Spring Boot+MyBatis架构下的典型问题(如大促时订单状态延迟、库存超卖误判及用户信息更新延迟)提出解决方案。核心内容包括动态数据源路由(强制读主库)、大事务拆分优化以及延迟感知补偿机制,配合MySQL参数调优和监控集成,有效将主从延迟控制在1秒内。实际测试表明,在10万QPS场景下,订单查询延迟显著降低,超卖误判率下降98%。
|
1月前
|
Ubuntu 关系型数据库 MySQL
在Ubuntu系统的Docker上安装MySQL的方法
以上的步骤就是在Ubuntu系统的Docker上安装MySQL的详细方法,希望对你有所帮助!
163 12
|
3月前
|
Java 关系型数据库 MySQL
SpringBoot 通过集成 Flink CDC 来实时追踪 MySql 数据变动
通过详细的步骤和示例代码,您可以在 SpringBoot 项目中成功集成 Flink CDC,并实时追踪 MySQL 数据库的变动。
703 43
|
3月前
|
人工智能 JavaScript 关系型数据库
【02】Java+若依+vue.js技术栈实现钱包积分管理系统项目-商业级电玩城积分系统商业项目实战-ui设计图figmaUI设计准备-figma汉化插件-mysql数据库设计-优雅草卓伊凡商业项目实战
【02】Java+若依+vue.js技术栈实现钱包积分管理系统项目-商业级电玩城积分系统商业项目实战-ui设计图figmaUI设计准备-figma汉化插件-mysql数据库设计-优雅草卓伊凡商业项目实战
146 14
【02】Java+若依+vue.js技术栈实现钱包积分管理系统项目-商业级电玩城积分系统商业项目实战-ui设计图figmaUI设计准备-figma汉化插件-mysql数据库设计-优雅草卓伊凡商业项目实战
|
2月前
|
Java 数据库 微服务
微服务——SpringBoot使用归纳——Spring Boot中的项目属性配置——指定项目配置文件
在实际项目中,开发环境和生产环境的配置往往不同。为简化配置切换,可通过创建 `application-dev.yml` 和 `application-pro.yml` 分别管理开发与生产环境配置,如设置不同端口(8001/8002)。在 `application.yml` 中使用 `spring.profiles.active` 指定加载的配置文件,实现环境快速切换。本节还介绍了通过配置类读取参数的方法,适用于微服务场景,提升代码可维护性。课程源码可从 [Gitee](https://gitee.com/eson15/springboot_study) 下载。
67 0
|
3月前
|
人工智能 关系型数据库 分布式数据库
100%兼容MySQL!手把手教你基于PolarDB搭建RAG系统
100%兼容MySQL!手把手教你基于PolarDB搭建RAG系统
176 0
|
2月前
|
XML Java 数据库连接
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于 xml 的整合
本教程介绍了基于XML的MyBatis整合方式。首先在`application.yml`中配置XML路径,如`classpath:mapper/*.xml`,然后创建`UserMapper.xml`文件定义SQL映射,包括`resultMap`和查询语句。通过设置`namespace`关联Mapper接口,实现如`getUserByName`的方法。Controller层调用Service完成测试,访问`/getUserByName/{name}`即可返回用户信息。为简化Mapper扫描,推荐在Spring Boot启动类用`@MapperScan`注解指定包路径避免逐个添加`@Mapper`
74 0
|
2月前
|
前端开发 Java 数据库
微服务——SpringBoot使用归纳——Spring Boot集成Thymeleaf模板引擎——Thymeleaf 介绍
本课介绍Spring Boot集成Thymeleaf模板引擎。Thymeleaf是一款现代服务器端Java模板引擎,支持Web和独立环境,可实现自然模板开发,便于团队协作。与传统JSP不同,Thymeleaf模板可以直接在浏览器中打开,方便前端人员查看静态原型。通过在HTML标签中添加扩展属性(如`th:text`),Thymeleaf能够在服务运行时动态替换内容,展示数据库中的数据,同时兼容静态页面展示,为开发带来灵活性和便利性。
75 0

热门文章

最新文章