1. 初始化 Spring Boot 项目
首先,使用 Spring Initializr 生成一个 Spring Boot 项目,并添加以下依赖:
<dependencies><!-- Spring Boot Starter Web --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- MyBatis Plus Starter --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.4.3.3</version></dependency><!-- MySQL Connector --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><!-- Lombok --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><!-- Spring Boot Starter Test (for testing purposes) --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
</dependencies>
2. 添加数据库配置
在 src/main/resources/application.properties 文件中添加数据库配置,并包含 user 表的 SQL 建表语句:
spring.datasource.url=jdbc:mysql://localhost:3306/your_database?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Drivermybatis-plus.mapper-locations=classpath:/mapper/*.xml
mybatis-plus.type-aliases-package=cn.shutdown.demo.model
# User 表的 SQL 建表语句
CREATE TABLE `user` (`id` bigint NOT NULL AUTO_INCREMENT,`name` varchar(255) DEFAULT NULL,`age` int DEFAULT NULL,`email` varchar(255) DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
确保数据库连接信息正确,并且已经创建了一个名为 your_database 的数据库。
创建 User 实体类
在 src/main/java/cn/shutdown/demo/model 目录下创建 User.java:
package cn.shutdown.demo.model;import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;@Data
@TableName("user")
public class User {@TableId(type = IdType.AUTO)private Long id;private String name;private Integer age;private String email;
}
创建 UserMapper 接口
在 src/main/java/cn/shutdown/demo/mapper 目录下创建 UserMapper.java:
package cn.shutdown.demo.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import cn.shutdown.demo.model.User;
import org.apache.ibatis.annotations.Mapper;@Mapper
public interface UserMapper extends BaseMapper<User> {// 这里不需要写额外的代码,因为 BaseMapper 已经提供了基本的 CRUD 操作
}
创建 UserService 接口和实现类
在 src/main/java/cn/shutdown/demo/service 目录下创建 IUserService.java 和 UserServiceImpl.java:
package cn.shutdown.demo.service;import com.baomidou.mybatisplus.extension.service.IService;
import cn.shutdown.demo.model.User;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;public interface IUserService extends IService<User> {IPage<User> selectUserPageByQuery(Page<User> page, UserQuery query);
}
package cn.shutdown.demo.service.impl;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.shutdown.demo.mapper.UserMapper;
import cn.shutdown.demo.model.User;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.shutdown.demo.model.UserQuery;public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {@Overridepublic IPage<User> selectUserPageByQuery(Page<User> page, UserQuery query) {// 这里可以根据query对象中的属性来构建动态的查询条件// 例如,使用MyBatis Plus的条件构造器return baseMapper.selectPage(page, getQueryWrapper(query));}private QueryWrapper<User> getQueryWrapper(UserQuery query) {QueryWrapper<User> queryWrapper = new QueryWrapper<>();if (query.getName() != null) {queryWrapper.like("name", query.getName());}if (query.getEmail() != null) {queryWrapper.like("email", query.getEmail());}// 可以根据需要添加更多的查询条件return queryWrapper;}
}
创建 UserController 类
在 src/main/java/cn/shutdown/demo/controller 目录下创建 UserController.java:
package cn.shutdown.demo.controller;import com.baomidou.mybatisplus.core.metadata.IPage;
import cn.shutdown.demo.model.User;
import cn.shutdown.demo.service.IUserService;
import cn.shutdown.demo.model.UserQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;import java.util.Optional;@RestController
public class UserController {@Autowiredprivate IUserService userService;@GetMapping("/users")public IPage<User> listUsers(@RequestParam(defaultValue = "1") int currentPage,@RequestParam(defaultValue = "10") int pageSize,@RequestParam(required = false) String name,@RequestParam(required = false) String email) {Page<User> page = new Page<>(currentPage, pageSize);UserQuery query = new UserQuery();query.setName(name);query.setEmail(email);return userService.selectUserPageByQuery(page, query);}
}
配置 MyBatis Plus 分页插件
在 src/main/java/cn/shutdown/demo/config 目录下创建 MyBatisPlusConfig.java:
package cn.shutdown.demo.config;import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class MybatisPlusConfig {@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();interceptor.addInnerInterceptor(new PaginationInnerInterceptor());return interceptor;}
}
运行项目
确保你的数据库已经运行,并且 user 表已经创建。运行 Spring Boot 应用程序,然后访问 http://localhost:8080/users?pageNum=1&pageSize=10 来测试分页查询。
添加模糊查询功能
如果需要添加模糊查询功能,可以按照之前的步骤进行扩展,添加 UserQuery 类、更新 UserService 和 UserMapper,并在 UserController 中添加新的接口。