当前位置: 首页 > news >正文

Spring Boot + MyBatis 实现 RESTful API 的完整流程


后端开发:Spring Boot 快速开发实战

引言

在现代后端开发中,Spring Boot 因其轻量级、快速开发的特性而备受开发者青睐。本文将带你从零开始,使用 Spring Boot + MyBatis 实现一个完整的 RESTful API,并深入探讨如何优雅地处理异常和日志记录。无论你是初学者还是有一定经验的开发者,这篇笔记都能为你提供实用的知识点。


一、环境准备

1. 安装依赖工具

确保你已经安装了以下工具:

  • JDK 8 或更高版本
  • Maven(构建工具)
  • IDE(如 IntelliJ IDEA 或 VS Code)

2. 创建 Spring Boot 项目

使用 Spring Initializr 快速生成项目骨架:

  1. 访问 Spring Initializr 网站。
  2. 配置项目信息:
    • Project: Maven Project
    • Language: Java
    • Spring Boot: 最新稳定版本
    • Dependencies: 添加 Spring Web, MyBatis Framework, MySQL Driver
  3. 下载并解压项目,导入到 IDE 中。

二、Spring Boot + MyBatis 实现 RESTful API 的完整流程

1. 数据库设计

假设我们要开发一个简单的用户管理系统,包含以下字段:

  • id (主键)
  • name (用户名)
  • email (邮箱)
SQL 脚本
CREATE DATABASE user_management;USE user_management;CREATE TABLE users (id BIGINT AUTO_INCREMENT PRIMARY KEY,name VARCHAR(100) NOT NULL,email VARCHAR(100) NOT NULL UNIQUE
);

2. 配置数据库连接

application.properties 文件中配置 MySQL 数据库连接信息:

spring.datasource.url=jdbc:mysql://localhost:3306/user_management?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver# MyBatis 配置
mybatis.mapper-locations=classpath:mapper/*.xml

3. 创建实体类

创建一个 User 实体类,与数据库表对应:

package com.example.demo.entity;public class User {private Long id;private String name;private String email;// Getters and Setters
}

4. 创建 Mapper 接口

使用 MyBatis 的注解或 XML 配置方式定义数据访问层接口:

package com.example.demo.mapper;import com.example.demo.entity.User;
import org.apache.ibatis.annotations.*;import java.util.List;@Mapper
public interface UserMapper {@Select("SELECT * FROM users")List<User> findAll();@Select("SELECT * FROM users WHERE id = #{id}")User findById(Long id);@Insert("INSERT INTO users(name, email) VALUES(#{name}, #{email})")@Options(useGeneratedKeys = true, keyProperty = "id")void insert(User user);@Update("UPDATE users SET name=#{name}, email=#{email} WHERE id=#{id}")void update(User user);@Delete("DELETE FROM users WHERE id=#{id}")void delete(Long id);
}

5. 创建 Service 层

封装业务逻辑,调用 Mapper 接口:

package com.example.demo.service;import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service
public class UserService {@Autowiredprivate UserMapper userMapper;public List<User> getAllUsers() {return userMapper.findAll();}public User getUserById(Long id) {return userMapper.findById(id);}public void createUser(User user) {userMapper.insert(user);}public void updateUser(User user) {userMapper.update(user);}public void deleteUser(Long id) {userMapper.delete(id);}
}

6. 创建 Controller 层

暴露 RESTful API 接口:

package com.example.demo.controller;import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.util.List;@RestController
@RequestMapping("/api/users")
public class UserController {@Autowiredprivate UserService userService;@GetMappingpublic List<User> getAllUsers() {return userService.getAllUsers();}@GetMapping("/{id}")public User getUserById(@PathVariable Long id) {return userService.getUserById(id);}@PostMappingpublic void createUser(@RequestBody User user) {userService.createUser(user);}@PutMapping("/{id}")public void updateUser(@PathVariable Long id, @RequestBody User user) {user.setId(id);userService.updateUser(user);}@DeleteMapping("/{id}")public void deleteUser(@PathVariable Long id) {userService.deleteUser(id);}
}

三、如何优雅地处理异常和日志记录?

1. 全局异常处理

使用 @ControllerAdvice 注解实现全局异常处理,避免重复代码:

package com.example.demo.exception;import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;@ControllerAdvice
public class GlobalExceptionHandler {@ExceptionHandler(Exception.class)public ResponseEntity<String> handleException(Exception ex) {return new ResponseEntity<>("An error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);}@ExceptionHandler(ResourceNotFoundException.class)public ResponseEntity<String> handleResourceNotFoundException(ResourceNotFoundException ex) {return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);}
}

自定义异常类:

package com.example.demo.exception;public class ResourceNotFoundException extends RuntimeException {public ResourceNotFoundException(String message) {super(message);}
}

2. 日志记录

使用 SLF4JLogback 记录日志,便于调试和问题追踪:

package com.example.demo.controller;import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.util.List;@RestController
@RequestMapping("/api/users")
public class UserController {private static final Logger logger = LoggerFactory.getLogger(UserController.class);@Autowiredprivate UserService userService;@GetMappingpublic List<User> getAllUsers() {logger.info("Fetching all users");return userService.getAllUsers();}@PostMappingpublic void createUser(@RequestBody User user) {logger.info("Creating user: {}", user);userService.createUser(user);}
}

四、总结

通过本文,我们完成了以下内容:

  1. 使用 Spring Boot 和 MyBatis 实现了一个完整的 RESTful API。
  2. 学习了如何优雅地处理异常和记录日志。

这些技能是后端开发的核心能力,能够帮助你在实际项目中快速构建高效、稳定的系统。希望这篇文章能为你提供实用的指导,并助力你在以后的只有我道路上有目标,向钱进!

参考链接

  • Spring Boot 官方文档
  • MyBatis 官方文档
  • RESTful API 设计指南

http://www.lryc.cn/news/545093.html

相关文章:

  • 通过 ANSYS Discovery 进行 CFD 分析,增强工程设计
  • 家用可燃气体探测器——家庭燃气安全的坚实防线
  • ListControl双击实现可编辑
  • ave-form.vue 组件中 如何将产品名称发送给后端 ?
  • DeepSeek行业应用实践报告-智灵动力【112页PPT全】
  • 【Markdown 语法简洁讲解】
  • 250301-OpenWebUI配置DeepSeek-火山方舟+硅基流动+联网搜索+推理显示
  • 【3天快速入门WPF】12-MVVM
  • 查找Excel包含关键字的行(の几种简单快速方法)
  • 性能测试分析和调优
  • (视频教程)Compass代谢分析详细流程及python版-R语言版下游分析和可视化
  • 【SQL】MySQL中的字符串处理函数:concat 函数拼接字符串,COALESCE函数处理NULL字符串
  • c++中深拷贝和浅拷贝的联系和区别
  • Autotestplat 在多个平台和公司推荐使用!
  • 字符串最后一个单词的长度
  • 【Linux】learning notes(3)make、copy、move、remove
  • 一、图像图像的基本概念
  • 两道算法练习
  • 利用 Python 爬虫进行跨境电商数据采集
  • 设计模式--spring中用到的设计模式
  • Qt控件中函数指针使用的最终版本,使用std::function
  • Java中的泛型类 --为集合的学习做准备
  • 6.6.6 嵌入式SQL
  • 基于C#的CANoe CLR Adapter开发指南
  • 【Qt】MVC设计模式
  • 【手撕算法】支持向量机(SVM)从入门到实战:数学推导与核技巧揭秘
  • JAVA面试常见题_基础部分_Dubbo面试题(上)
  • CSS—隐藏元素:1分钟掌握与使用隐藏元素的方法
  • 二、双指针——5. 移动零
  • 论文笔记-NeurIPS2017-DropoutNet