浪漫编码:手把手教你实现校园表白墙功能

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
云数据库 RDS PostgreSQL,高可用系列 2核4GB
简介: 浪漫编码:手把手教你实现校园表白墙功能

表白墙

前面的案例中,我们写了表白墙,但是⼀旦服务器重启,数据仍然会丢失.

要想数据不丢失,需要把数据存储在数据库中.接下来咱们借助MyBatis来实现数据的操作


数据准备

DROP TABLE IF EXISTS message_info;
  CREATE TABLE `message_info` (
  `id` INT ( 11 ) NOT NULL AUTO_INCREMENT,
  `from` VARCHAR ( 127 ) NOT NULL,
  `to` VARCHAR ( 127 ) NOT NULL,
  `message` VARCHAR ( 256 ) NOT NULL,
  `delete_flag` TINYINT ( 4 ) DEFAULT 0 COMMENT '0-正常, 1-删除',
  `create_time` DATETIME DEFAULT now(),
  `update_time` DATETIME DEFAULT now() ON UPDATE now(),
  PRIMARY KEY ( `id` )
) ENGINE = INNODB DEFAULT CHARSET = utf8mb4;

ONUPDATEnow():当数据发生更新操作时,自动把该列的值设置为now(),

now()可以替换成其他获取时间的标识符,⽐如:CURRENT_TIMESTAMP(),LOCALTIME()等MySQL<5.6.5

  1. 只有TIMESTAMP⽀持自动更新
  2. ⼀个表只能有⼀列设置自动更新
  3. 不允许同时存在两个列,其中⼀列设置了DEFAULTCURRENT_TIMESTAMP,]
  4. TIMESTAMP和DATETIME都⽀持自动更新,且可以有多列

引入MyBatis和MySQL驱动依赖

修改pom文件

<dependency>
  <groupId>org.mybatis.spring.boot</groupId>
  <artifactId>mybatis-spring-boot-starter</artifactId>
  <version>3.0.3</version>
</dependency>
<dependency>
  <groupId>com.mysql</groupId>
  <artifactId>mysql-connector-j</artifactId>
  <scope>runtime</scope>
</dependency>

或者使用插件EditStarters来引入依赖

配置MySQL账号密码

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/mybatis_test?
characterEncoding=utf8&useSSL=false
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
  configuration: # 配置打印 MyBatis⽇志
    map-underscore-to-camel-case: true #配置驼峰自动转换

编写后端代码

import lombok.Data;
@Data
public class MessageInfo {
  private Integer id;
  private String from;
  private String to;
  private String message;
  private Integer deleteFlag;
  private Date createTime;
  private Date updateTime;
}

MessageInfoMapper

import com.example.demo.model.MessageInfo;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface MessageInfoMapper {
  @Select("select `id`, `from`, `to`, `message` from message_info where delete_flag=0")
  List<MessageInfo> queryAll();
  
  @Insert("insert into message_info (`from`,`to`, `message`) values(#{from},#{to},#{message})")
  Integer addMessage(MessageInfo messageInfo);
}

MessageInfoService

import com.example.demo.mapper.MessageInfoMapper;
import com.example.demo.model.MessageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class MessageInfoService {
  @Autowired
  private MessageInfoMapper messageInfoMapper;
  
  public List<MessageInfo> queryAll() {
    return messageInfoMapper.queryAll();
  }
  
  public Integer addMessage(MessageInfo messageInfo) {
    return messageInfoMapper.addMessage(messageInfo);
  }
}

MessageController

import com.example.demo.model.MessageInfo;
import com.example.demo.service.MessageInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RequestMapping("/message")
@RestController
public class MessageController {
    @Autowired
    private MessageInfoService messageInfoService;
    /**
     * 获取留言列表
     * @return
     */
    @RequestMapping("/getList")
    public List<MessageInfo> getList() {
        return messageInfoService.queryAll();
    }
    /**
     * 发表留言
     * @param messageInfo
     * @return
     */
    @RequestMapping("/publish")
    public boolean publish(MessageInfo messageInfo) {
        System.out.println(messageInfo);
        if (StringUtils.hasLength(messageInfo.getFrom())
                && StringUtils.hasLength(messageInfo.getTo())
                && StringUtils.hasLength(messageInfo.getMessage())) {
            messageInfoService.addMessage(messageInfo);
            return true;
        }
        return false;
    }
}


测试代码

部署程序,验证服务器是否能正确响应:http://127.0.0.1:8080/messagewall.html

输入留言信息,点击提交,发现页面列表显示新的数据,并且数据库中也添加了⼀条记录.

重启服务,页面显示不变.

相关实践学习
如何快速连接云数据库RDS MySQL
本场景介绍如何通过阿里云数据管理服务DMS快速连接云数据库RDS MySQL,然后进行数据表的CRUD操作。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
打赏
0
0
0
0
15
分享
相关文章
使用蒙特卡罗模拟的投资组合优化
在金融市场中,优化投资组合对于实现风险与回报之间的预期平衡至关重要。蒙特卡罗模拟提供了一个强大的工具来评估不同的资产配置策略及其在不确定市场条件下的潜在结果。
596 1
软件工程IT项目管理复习之 十二:项目采购管理
软件工程IT项目管理复习之 十二:项目采购管理
354 0
Element_select 选择器 选中框中显示不了选中的值
解决Vue中`el-select`选择器不显示选中值的问题:在`selectChanged`方法中添加`this.$forceUpdate()`,强制组件更新,使输入框显示选择的值。示例代码包括模板和方法。
1179 2
每个端侧产品都需要的用户体验监控
ARMS RUM 是阿里云应用实时监控服务(ARMS)下的用户体验监控(RUM)产品,覆盖 Web/H5、各类平台小程序、Android、iOS、Flutter、ReactNative、Windows、macOS 等平台框架。接入 SDK 后会主动采集端侧页面性能、资源加载、API 调用、异常崩溃、卡顿、用户操作、系统信息等数据,还支持事件、日志、异常等数据按需自定义上报以满足业务数据分析需求,提供全面的性能分析、异常分析、产品分析、会话分析能力,帮助快速跟踪定位问题原因,提升产品用户使用体验。
739 85
Vue.js是什么
【8月更文挑战第28天】Vue.js是什么
223 0
【企业实践】台州银行携手瓴羊Dataphin共建数据平台,打造小微金融治理新标杆
台州银行数据治理项目携手瓴羊Dataphin,荣获中国信息通信研究院评为“2023年铸基计划高质量数字化转型典型优秀案例”、数字化研究机构沙丘社区选为“2024中国数据资产管理最佳实践案例”双重认可。
789 4
【企业实践】台州银行携手瓴羊Dataphin共建数据平台,打造小微金融治理新标杆
基于SSM框架的购物商城系统设计与实现
基于SSM框架的购物商城系统设计与实现
428 2
知识图谱(Knowledge Graph)- Neo4j 5.10.0 Docker 安装
知识图谱(Knowledge Graph)- Neo4j 5.10.0 Docker 安装
277 0

热门文章

最新文章

AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等

登录插画

登录以查看您的控制台资源

管理云资源
状态一览
快捷访问