一、引言
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文件上传至服务器,并通过命令启动: