目录
之前的项目实例【基于Spring MVC的前后端交互案例及应用分层的实现】https://blog.csdn.net/weixin_67793092/article/details/134613210?utm_source=app&app_version=6.1.7中有关对于留言板的介绍,现在使用Mybatis完成连接数据库,这样以便刷新浏览器页面后,之前输入的信息仍然能够保存在硬盘中。
之前的前端页面实现:
1.添加Mybatis和SQL的依赖
在pom.xml文件中右键
2.建立数据库和需要的表
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;
配置连接数据库application.properties文件
java
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mybatis_test?characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
3.对应表中的字段,补充Java对象
4.对代码进行逻辑分层
controller接收请求,service服务层实现业务逻辑,mapper查询数据库的操作,model存放对象。
配置日志:
方便遇见问题时调试代码
mybatis:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
5.后端逻辑代码
MessageController
java
@Slf4j
@RequestMapping("/message")
@RestController
//发布留言
public class MessageController {
// private List<MessageInfo> messageInfos=new ArrayList<>();
@Autowired
private MessageService messageService;
@RequestMapping("/publish")
public Boolean publishMessage(MessageInfo messageInfo) {
log.info("发表留言");
//进行参数的校验
if (!StringUtils.hasLength(messageInfo.getFrom())
|| !StringUtils.hasLength(messageInfo.getTo())
|| !StringUtils.hasLength(messageInfo.getMessage())) {
return false;
}
//添加留言
messageService.addMessage(messageInfo);
return true;
}
// 查看留言
@RequestMapping("/getMassageInfo")
public List<MessageInfo> getMessageInfo(){
return messageService.getMessageInfo();
}
}
MessageService
java
@Service
public class MessageService {
@Autowired
private MessageMapper messageMapper;
public void addMessage(MessageInfo messageInfo) {
messageMapper.insertMessage(messageInfo);
}
public List<MessageInfo> getMessageInfo() {
return messageMapper.selectAllMessage();
}
}
MessageMapper
java
@Mapper
public interface MessageMapper {
@Insert("insert into message_info(from,to,message) values (#{from},#{to},#{message}")
void insertMessage(MessageInfo messageInfo);
@Select("select * from message_info where delete_flag=0")
List<MessageInfo> selectAllMessage();
}
代码逻辑: