一、引言
1. 項目背景與目標
在現代Web開發中,CRUD(創建、讀取、更新、刪除)操作是幾乎所有應用程序的核心功能。本項目旨在通過Spring Boot、MyBatis和MySQL技術棧,快速搭建一個高效、簡潔的CRUD應用。我們將從零開始,逐步實現一個用戶管理系統的增刪改查功能。
2. 技術選型與適用場景
- Spring Boot:簡化了基于Spring的應用開發,提供了自動配置、嵌入式服務器等特性。
- MyBatis:作為持久層框架,支持自定義SQL、存儲過程和高級映射,靈活性高。
- MySQL:廣泛使用的開源關系型數據庫,性能穩定,社區活躍。
二、開發環境準備
1. 開發工具與依賴安裝
- JDK:確保已安裝Java Development Kit(建議版本8及以上)。
- Maven/Gradle:用于項目構建和依賴管理。
- IDE:推薦使用IntelliJ IDEA或Eclipse。
- MySQL:下載并安裝MySQL數據庫,配置好數據庫連接信息。
2. Spring Boot項目初始化
- 使用 Spring Initializr 創建項目:
- Project: Maven Project
- Language: Java
- Spring Boot: 最新穩定版本
- Dependencies: Spring Web, MyBatis Framework, MySQL Driver
三、數據庫設計與初始化
1. MySQL數據庫表設計
創建一個簡單的用戶表user
,包含以下字段:
CREATE TABLE user (id INT AUTO_INCREMENT PRIMARY KEY,username VARCHAR(50) NOT NULL UNIQUE,password VARCHAR(100) NOT NULL,email VARCHAR(100),created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
2. 數據初始化腳本
在src/main/resources
目錄下創建data.sql
文件,插入一些測試數據:
INSERT INTO user (username, password, email) VALUES
('admin', 'password123', 'admin@example.com'),
('user1', 'password123', 'user1@example.com');
配置application.yml
中的數據庫連接信息:
spring:datasource:url: jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTCusername: rootpassword: rootdriver-class-name: com.mysql.cj.jdbc.Driver
四、Spring Boot與MyBatis集成
1. MyBatis基礎配置
在application.yml
中添加MyBatis配置:
mybatis:mapper-locations: classpath:mapper/*.xmltype-aliases-package: com.example.demo.entity
2. 實體類與Mapper接口開發
-
實體類:創建
User
類表示用戶信息。package com.example.demo.entity;public class User {private Integer id;private String username;private String password;private String email;private Timestamp createdAt;// Getters and Setters }
-
Mapper接口:創建
UserMapper
接口及對應的XML映射文件。package com.example.demo.mapper;import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select;@Mapper public interface UserMapper {@Select("SELECT * FROM user WHERE id = #{id}")User findById(Integer id); }
在
src/main/resources/mapper
目錄下創建UserMapper.xml
:<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.example.demo.mapper.UserMapper"><select id="findById" resultType="com.example.demo.entity.User">SELECT * FROM user WHERE id = #{id}</select> </mapper>
3. Service層與Controller層實現
-
Service層:封裝業務邏輯。
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;@Service public class UserService {@Autowiredprivate UserMapper userMapper;public User getUserById(Integer id) {return userMapper.findById(id);} }
-
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.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController;@RestController public class UserController {@Autowiredprivate UserService userService;@GetMapping("/users/{id}")public User getUser(@PathVariable Integer id) {return userService.getUserById(id);} }
五、CRUD功能實現
1. 創建(Create)功能
-
Mapper接口:添加插入數據的方法。
@Insert("INSERT INTO user (username, password, email) VALUES (#{username}, #{password}, #{email})") void insertUser(User user);
-
Service層:實現新增用戶邏輯。
public void createUser(User user) {userMapper.insertUser(user); }
-
Controller層:提供新增用戶的API接口。
@PostMapping("/users") public void createUser(@RequestBody User user) {userService.createUser(user); }
2. 讀取(Read)功能
- 分頁查詢:使用MyBatis分頁插件PageHelper。
<select id="findAllUsers" resultType="com.example.demo.entity.User">SELECT * FROM user </select>
PageHelper.startPage(pageNum, pageSize);List<User> users = userMapper.findAllUsers();PageInfo<User> pageInfo = new PageInfo<>(users);
- 動態條件查詢:按用戶名模糊搜索。
<select id="findUsersByUsername" resultType="com.example.demo.entity.User">SELECT * FROM user WHERE username LIKE CONCAT('%', #{username}, '%') </select>
3. 更新(Update)功能
-
Mapper接口:添加更新數據的方法。
@Update("UPDATE user SET username=#{username}, password=#{password}, email=#{email} WHERE id=#{id}") void updateUser(User user);
-
Service層:實現更新用戶邏輯。
public void updateUser(User user) {userMapper.updateUser(user); }
-
Controller層:提供更新用戶的API接口。
@PutMapping("/users/{id}") public void updateUser(@PathVariable Integer id, @RequestBody User user) {user.setId(id);userService.updateUser(user); }
4. 刪除(Delete)功能
-
硬刪除:直接從數據庫中刪除記錄。
@Delete("DELETE FROM user WHERE id=#{id}") void deleteUserById(Integer id);
-
軟刪除:添加
is_deleted
字段標記刪除狀態。ALTER TABLE user ADD COLUMN is_deleted TINYINT DEFAULT 0;
@Update("UPDATE user SET is_deleted=1 WHERE id=#{id}")void softDeleteUserById(Integer id);
六、功能擴展與優化
1. 事務管理
- @Transactional注解:確保多個操作在同一事務中執行。
@Service @Transactional public class UserService {// CRUD方法 }
2. 分頁與排序
-
PageHelper分頁插件:實現分頁查詢。
<dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper-spring-boot-starter</artifactId><version>1.4.0</version> </dependency>
-
排序參數動態傳入:根據請求參數進行排序。
PageHelper.startPage(pageNum, pageSize).setOrderBy(orderBy);
3. 異常處理
- 全局異常捕獲:使用
@ControllerAdvice
處理全局異常。@ControllerAdvice public class GlobalExceptionHandler {@ExceptionHandler(Exception.class)public ResponseEntity<String> handleException(Exception e) {return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());} }
七、測試與部署
1. 單元測試與集成測試
-
單元測試:編寫Mapper接口測試用例。
@RunWith(SpringRunner.class) @SpringBootTest public class UserMapperTest {@Autowiredprivate UserMapper userMapper;@Testpublic void testFindById() {User user = userMapper.findById(1);assertNotNull(user);} }
-
集成測試:驗證CRUD功能完整性。
@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class UserControllerIT {@Autowiredprivate TestRestTemplate restTemplate;@Testpublic void testGetUser() {ResponseEntity<User> response = restTemplate.getForEntity("/users/1", User.class);assertEquals(HttpStatus.OK, response.getStatusCode());} }
2. 項目打包與部署
-
打包為可執行JAR文件:
mvn clean package
-
部署到本地Tomcat或云服務器:
- 將生成的JAR文件上傳至服務器,并通過命令啟動:
java -jar myapp.jar
- 將生成的JAR文件上傳至服務器,并通過命令啟動: