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

本文介绍了如何从零开始,利用MyBatis框架和MySQL数据库为校园表白墙功能实现数据持久化,包括创建数据库表、配置MyBatis依赖、编写后端接口以及测试代码,确保数据在服务器重启后仍能保留。
摘要由CSDN通过智能技术生成

在这里插入图片描述
💓 博客主页:从零开始的-CodeNinja之路

⏩ 收录文章:浪漫编码:手把手教你实现校园表白墙功能

🎉欢迎大家点赞👍评论📝收藏⭐文章
在这里插入图片描述
在这里插入图片描述

表白墙

前面的案例中,我们写了表白墙,但是⼀旦服务器重启,数据仍然会丢失.
要想数据不丢失,需要把数据存储在数据库中.接下来咱们借助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
在这里插入图片描述
输入留言信息,点击提交,发现页面列表显示新的数据,并且数据库中也添加了⼀条记录.
在这里插入图片描述

在这里插入图片描述
重启服务,页面显示不变.

  • 105
    点赞
  • 96
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 162
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

从零开始的-CodeNinja之路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值