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.pswp.cn/bicheng/72196.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/72196.shtml
英文地址,請注明出處:http://en.pswp.cn/bicheng/72196.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

使用Python開發以太坊智能合約:輕松入門與深度探索

使用Python開發以太坊智能合約&#xff1a;輕松入門與深度探索 隨著區塊鏈技術的快速發展&#xff0c;以太坊作為最為成熟和廣泛使用的智能合約平臺&#xff0c;成為了開發去中心化應用&#xff08;DApp&#xff09;的核心工具。智能合約不僅是區塊鏈技術的基礎&#xff0c;更…

ES scroll=1m:表示快照的有效時間為1分鐘。怎么理解

在Elasticsearch中&#xff0c;scroll1m 表示你創建的 scroll 上下文 的有效時間為 1分鐘。這個參數控制了你可以在多長時間內繼續使用這個 scroll_id 來獲取更多的數據。 什么是 Scroll 上下文&#xff1f; 當你使用 scroll API 時&#xff0c;Elasticsearch 會為你的查詢創…

Linux與UDP應用1:翻譯軟件

UDP應用1&#xff1a;翻譯軟件 本篇介紹 本篇基于UDP編程接口基本使用中封裝的服務器和客戶端進行改寫&#xff0c;基本功能如下&#xff1a; 從配置文件dict.txt讀取到所有的單詞和意思客戶端向服務端發送英文服務端向客戶端發送英文對應的中文意思 配置文件內容 下面的內…

Jeecg-Boot 開放接口開發實戰:在 Jeecg-Boot 的jeecg-system-biz中添加一個controller 實現免鑒權數據接口

Jeecg-Boot 開放接口開發實戰&#xff1a;在 Jeecg-Boot 的jeecg-system-biz中添加一個controller 實現免鑒權數據接口 一、場景需求分析 在微服務架構中&#xff0c;常需要快速實現以下兩類接口&#xff1a; 開放接口&#xff1a;無需登錄即可訪問&#xff08;如數據查詢、…

C++ ++++++++++

初始C 注釋 變量 常量 關鍵字 標識符命名規則 數據類型 C規定在創建一個變量或者常量時&#xff0c;必須要指定出相應的數據類型&#xff0c;否則無法給變量分配內存 整型 sizeof關鍵字 浮點型&#xff08;實型&#xff09; 有效位數保留七位&#xff0c;帶小數點。 這個是保…

構建安全的Docker基礎鏡像:從最佳實踐到自動化加固

引言 容器化技術的普及使得Docker鏡像成為軟件交付的核心載體,但鏡像中的安全漏洞、敏感信息泄露和權限配置不當等問題可能引發嚴重風險。本文結合OWASP容器安全指南與一線運維經驗,系統化講解如何構建安全的Docker基礎鏡像,覆蓋鏡像構建、依賴管理、運行時防護全鏈路,并提…

BKA-CNN基于黑翅鳶算法優化卷積神經網絡的數據多特征分類預測Matlab

BKA-CNN基于黑翅鳶算法優化卷積神經網絡的數據多特征分類預測Matlab 目錄 BKA-CNN基于黑翅鳶算法優化卷積神經網絡的數據多特征分類預測Matlab分類效果基本介紹BKA-CNN基于黑翅鳶算法優化卷積神經網絡的數據多特征分類預測一、引言1.1、研究背景和意義1.2、研究現狀1.3、研究目…

SOLID Principle基礎入門

(Robert C. Martin (Uncle Bob)) 什么是SOLID原則&#xff1f; SOLID原則是面向對象編程&#xff08;OOP&#xff09;中編寫高質量代碼的指導方針。實際上&#xff0c;即使不使用SOLID原則&#xff0c;僅通過類、繼承、封裝和多態性&#xff0c;也可以讓程序正常運行。那么為…

輕松實現語音生成:GPT-SoVITS V2整合包的遠程訪問操作詳解

文章目錄 前言1.GPT-SoVITS V2下載2.本地運行GPT-SoVITS V23.簡單使用演示4.安裝內網穿透工具4.1 創建遠程連接公網地址 5. 固定遠程訪問公網地址 前言 今天要給大家安利一個絕對能讓你大呼過癮的聲音黑科技——GPT-SoVITS&#xff01;這款由花兒不哭大佬精心打造的語音克隆神…

Python線程池知多少

目錄 目標 Python版本 官方文檔 概述 線程池 實戰 創建線程池的基本語法 批量提交任務 生產者&消費者模型 目標 掌握線程池的基本概念和使用方法。 Python版本 Python 3.9.18 官方文檔 concurrent.futures — Launching parallel taskshttps://docs.python.org/3…

(轉)SpringBoot和SpringCloud的區別

&#xff08;轉&#xff09;SpringBoot和SpringCloud的區別&#xff1a;

中科大 計算機網絡組成原理 1.4 接入網和物理媒體 筆記

一、接入網核心功能與架構 ?核心作用? 接入網是連接用戶終端與核心網絡的橋梁&#xff0c;承擔用戶身份認證、帶寬分配、數據加密等功能&#xff0c;直接影響網絡服務的可靠性和用戶體驗。例如&#xff0c;杭州電視臺的數字人主播通過光纖專線實現零失誤新聞播報&#xff0c;…

阿里云音頻算法崗內推

1、視頻云直播、連麥&#xff0c;點播&#xff0c;短視頻&#xff0c;媒體生產與處理等服務相關的實時/非實時的音頻分析和處理&#xff1b; 2、音頻處理算法&#xff0c;包括多場景降噪、自動增益控制、回聲消除等&#xff1b; 3、音頻特效算法研發&#xff0c;包括變調變速…

如何使用DeepSeek輔助準備面試

前言 又到了金三銀四的時間點了。每年的這個時間點都會出現無數的機遇和機會&#xff0c;但是如何準備面試&#xff0c;應該準備哪些面試題&#xff0c;如何查漏補缺我們的技術面的短板&#xff0c;這是我們每次準備面試的時候&#xff0c;都會遇見的問題。在今年&#xff0c;…

如何流暢訪問github

1.傳輸數據原理 本地計算機通過本地網接入運營骨干網&#xff0c;經過DNS域名解析&#xff0c;將輸入的字符解析為要連接的真實IP地址&#xff0c;服務器返還一個數據包(github)給計算機 2.原因 DNS域名污染-DNS解析出現問題&#xff0c;導致訪問一個不存在的服務器 3.解決…

JPA屬性轉換器的使用與實例解析

在Java持久化框架中&#xff0c;JPA&#xff08;Java Persistence API&#xff09;為我們提供了強大的功能來操作數據庫。其中&#xff0c;屬性轉換器&#xff08;Attribute Converter&#xff09;是一個非常實用的特性&#xff0c;它允許我們將實體類中的屬性類型轉換為適合存…

AI數據分析:用DeepSeek做數據清洗

在當今數據驅動的時代&#xff0c;數據分析已成為企業和個人決策的重要工具。隨著人工智能技術的快速發展&#xff0c;AI 驅動的數據分析工具正在改變我們處理和分析數據的方式。本文將著重介紹如何使用 DeepSeek 進行數據清洗。 數據清洗是數據分析的基礎&#xff0c;其目的是…

rust學習~tokio的io

await Suspend execution until the result of a Future is ready. 暫停執行&#xff0c;直到一個 Future 的結果就緒。 .awaiting a future will suspend the current function’s execution until the executor has run the future to completion. 對一個 Future 使用 .awa…

騰訊2025年軟件測試面試題

以下是基于騰訊等一線互聯網公司軟件測試崗位的面試趨勢和技術要求,025年出現的軟件測試面試題。這些問題涵蓋了基礎知識、自動化測試、性能測試、安全測試、編程能力等多個方面,供參考和準備。 一、基礎知識 軟件測試的基本概念

數據結構(陳越,何欽銘) 第四講 樹(中)

4.1 二叉搜索樹 4.1.1 二叉搜索樹及查找 Position Find(ElementTyoe X,BinTree BST){if(!BST){return NULL;}if(X>BST->Data){return Find(X,BST->Right)}else if(X<BST->Data){return Find(X,BST->Left)}else{return BST;} } Position IterFind(ElementTyp…