一、项目结构

二、详细代码
1、config
MybatisPlusConfig
kotlin
package com.example.springbootmybatisplus.config;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
//选中关键字alt+enter:导入相关依赖
/**
* 拦截 update 和 delete 语句 作用:于防止恶意的全表更新和删除操作
* */
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
return interceptor;
}
}
2、entity
User
typescript
package com.example.springbootmybatisplus.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.*;
import java.io.Serializable;
@Data
@AllArgsConstructor
@Getter
@Setter
@TableName("user")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private String username;
private String password;
private String email;
private String city;
@TableField(exist = false)
private String sex;
@TableField(exist = false)
private Long userId;
@TableField(exist = false)
private UserInfo userInfo;
public UserInfo getUserInfo() {
return userInfo;
}
public void setUserInfo(UserInfo userInfo) {
this.userInfo = userInfo;
}
public User() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
}
UserInfo
typescript
package com.example.springbootmybatisplus.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
@Data
@AllArgsConstructor
@Getter
@Setter
@TableName("userInfo")
public class UserInfo implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private String company;
private String job;
private String year;
private Long UserId;
public UserInfo() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public Long getUserId() {
return UserId;
}
public void setUserId(Long userId) {
UserId = userId;
}
}
3、对象封装vo
UserReqVO
typescript
package com.example.springbootmybatisplus.vo;
import lombok.Data;
import java.io.Serializable;
@Data
public class UserReqVO implements Serializable{
private static final long serialVersionUID = 1L;
private Long id;
private String username;
private String password;
private String email;
private String city;
private String sex;
private Long userId;
private Integer pageNum;
private Integer pageSize;
private Integer total;
public UserReqVO() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Integer getPageNum() {
return pageNum;
}
public void setPageNum(Integer pageNum) {
this.pageNum = pageNum;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
}
4、controller
TestController
less
package com.example.springbootmybatisplus.controller;
import com.example.springbootmybatisplus.entity.User;
import com.example.springbootmybatisplus.mapper.UserMapper;
import com.example.springbootmybatisplus.service.IUserService;
import com.example.springbootmybatisplus.vo.UserReqVO;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/user")
public class TestController {
@Autowired
private UserMapper userMapper;
@Resource
private IUserService userservice;
//查询列表
@GetMapping("/getUserList")
public List<User> list() {
// return userMapper.selectList( null);
return userservice.selectUserList();
}
//分页查询
@GetMapping("/getUserListPage")
public PageInfo<User> listPage() {
return userservice.selectUserListPage(1, 2);
}
//带条件的分页查询
@GetMapping("/getserchListPage")
public PageInfo<User> serchListPage(
@RequestParam(defaultValue = "1") int currentPage,
@RequestParam(defaultValue = "2") int pageSize,
@RequestParam(required = false) Long id,
@RequestParam(required = false) String username,
@RequestParam(required = false) String password,
@RequestParam(required = false) String email,
@RequestParam(required = false) String city
) {
return userservice.selectListPage(currentPage, pageSize, id, username, password, email, city);
}
/**
*
*封装
* @return
*/
@GetMapping("/selectUserObjListPage")
public PageInfo<User> selectUserObjListPage(UserReqVO user) {
return userservice.selectUserObjListPage(user);
}
/**
*
*新增和修改功能
* @return
*/
@PostMapping("/addAndeditUser")
public int addAndeditUser(@RequestBody UserReqVO user) {
return userservice.saveOrUpdate(user);
}
/**
*
*删除功能
* @return
*/
@GetMapping("/deleteUser")
public int deleteUser(@RequestParam Long id) {
return userservice.deleteById(id);
}
/**
*
*根据id查询详情功能
* @return
*/
@GetMapping("/getUserById")
public User getUserById(@RequestParam Long id) {
return userservice.selectById(id);
}
}
5、mapper
UserMapper
java
package com.example.springbootmybatisplus.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.springbootmybatisplus.entity.User;
import org.apache.ibatis.annotations.Mapper;
/**
* 继承User
* **/
@Mapper
public interface UserMapper extends BaseMapper<User> {
// 不需要添加其他注解或特殊配置
}
UserInfoMapper
kotlin
package com.example.springbootmybatisplus.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.springbootmybatisplus.entity.UserInfo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface UserInfoMapper extends BaseMapper<UserInfo> {
@Select("SELECT id,company,job,year,user_id FROM userInfo WHERE user_id = #{userId}")
UserInfo selectByUserId(@Param("userId") Long userId);
// 不需要添加其他注解或特殊配置
}
6、service
IUserService
java
package com.example.springbootmybatisplus.service;
import com.example.springbootmybatisplus.entity.User;
import com.example.springbootmybatisplus.vo.UserReqVO;
import com.github.pagehelper.PageInfo;
import java.util.List;
public interface IUserService {
List<User> selectUserList();
//分页查询
PageInfo<User> selectUserListPage(int pageNum, int pageSize);
/**
* 根据条件分页查询用户
* @param currentPage 当前页码
* @param pageSize 每页大小
* @param id 用户ID
* @param username 用户名
* @param password 密码
* @param email 邮箱
* @param city 城市
* @return 分页结果
*/
PageInfo<User> selectListPage(int currentPage, int pageSize, Long id, String username, String password, String email, String city);
PageInfo<User> selectUserObjListPage(UserReqVO user);
int saveOrUpdate(UserReqVO user);
int deleteById(Long id);
User selectById(Long id);
}
impl->UserServiceImpl
scss
package com.example.springbootmybatisplus.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.springbootmybatisplus.entity.User;
import com.example.springbootmybatisplus.entity.UserInfo;
import com.example.springbootmybatisplus.mapper.UserInfoMapper;
import com.example.springbootmybatisplus.mapper.UserMapper;
import com.example.springbootmybatisplus.service.IUserService;
import com.example.springbootmybatisplus.vo.UserReqVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import java.util.List;
@Service
public class UserServiceImpl implements IUserService {
@Resource
private UserMapper userMapper;
@Resource
private UserInfoMapper userInfoMapper;
@Override
public List<User> selectUserList() {
return userMapper.selectList( null);
}
@Override
public PageInfo<User> selectUserListPage(int pageNum, int pageSize) {
//这是mybatis提供的分页插件
PageHelper.startPage(pageNum, pageSize);
List<User> userList = userMapper.selectList(null);//这个queryWrapper就是查询的sql条件
return new PageInfo<>(userList);//返回的这个PageInfo对象,封装了分页的详细信息 数据集合 页码 页数 总数等都有
}
//根据条件分页查询
@Override
public PageInfo<User> selectListPage(int currentPage, int pageSize,
Long id, String username, String password,
String email, String city){
// 构造分页对象
PageHelper.startPage(currentPage, pageSize);
// 构造查询条件
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
// 添加各字段查询条件
if (id != null) {
queryWrapper.eq(User::getId, id);
}
if (StringUtils.hasText(username)) {
queryWrapper.like(User::getUsername, username);
}
if (StringUtils.hasText(password)) {
queryWrapper.eq(User::getPassword, password);
}
if (StringUtils.hasText(email)) {
queryWrapper.like(User::getEmail, email);
}
if (StringUtils.hasText(city)) {
queryWrapper.like(User::getCity, city);
}
List<User> selsetList = userMapper.selectList(queryWrapper);
// 执行分页查询
return new PageInfo<>(selsetList);
}
@Override
public PageInfo<User> selectUserObjListPage(UserReqVO user) {
if(ObjectUtils.isEmpty(user)){
throw new RuntimeException("参数错误");
}
// 构造分页对象
PageHelper.startPage(user.getPageNum(), user.getPageSize());
// 构造查询条件
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
// 添加各字段查询条件
if (user.getId() != null) {
queryWrapper.eq(User::getId, user.getId());
}
if (StringUtils.hasText(user.getUsername())) {
queryWrapper.like(User::getUsername, user.getUsername());
}
if (StringUtils.hasText(user.getPassword())) {
queryWrapper.eq(User::getPassword, user.getPassword());
}
if (StringUtils.hasText(user.getEmail())) {
queryWrapper.like(User::getEmail, user.getEmail());
}
if (StringUtils.hasText(user.getCity())) {
queryWrapper.like(User::getCity, user.getCity());
}
List<User> selsetList = userMapper.selectList(queryWrapper);
// 执行分页查询
return new PageInfo<>(selsetList);
}
//新增或修改
@Override
public int saveOrUpdate(UserReqVO user) {
if(ObjectUtils.isEmpty(user)){
throw new RuntimeException("参数错误");
}
User user1 = new User();
user1.setId(user.getId());
user1.setUsername(user.getUsername());
user1.setPassword(user.getPassword());
user1.setEmail(user.getEmail());
user1.setCity(user.getCity());
user1.setSex(user.getSex());
user1.setUserId(user.getUserId());
if(user.getId() == null){
return userMapper.insert(user1);
}else{
return userMapper.updateById(user1);
}
}
@Override
public int deleteById(Long id) {
if(id != null){
return userMapper.deleteById(id);
}else {
throw new RuntimeException("请传入id");
}
}
@Override
public User selectById(Long id) {
if (id != null){
//查询主表信息
User user = userMapper.selectById(id);
//查询附表userid对应的信息
UserInfo userInfo = userInfoMapper.selectByUserId(id);
//将明细表的数据封装进主表
user.setUserInfo(userInfo);
return user;
}else{
throw new RuntimeException("请传入id");
}
}
}
7、启动类SpringBootMybatisPlusApplication
typescript
package com.example.springbootmybatisplus;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootMybatisPlusApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootMybatisPlusApplication.class, args);
}
}
8、数据库连接
application.properties
ini
spring.application.name=SpringBoot-mybatis-plus
spring.datasource.url=jdbc:mysql://localhost:3306/wj
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# MyBatis-Plus??
mybatis-plus.mapper-locations=classpath*:mapper/**/*.xml
mybatis-plus.type-aliases-package=org.example.demojavatestinfo.entity
mybatis-plus.configuration.map-underscore-to-camel-case=true
application.yml
yaml
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/wj
username: root
password: 123456
hikari:
minimum-idle: 5
maximum-pool-size: 20
auto-commit: true
idle-timeout: 30000
pool-name: HikariCP
max-lifetime: 1800000
connection-timeout: 30000
三、相关注解解释及作用
类级别注解
1. @RestController
css
@RestController
- 含义 : 组合注解,相当于
@Controller
+@ResponseBody
- 作用: 表明该类是一个RESTful风格的控制器,所有方法的返回值都会自动序列化为JSON格式
- 用法: 用于定义REST API的控制器类
2. @RequestMapping("/user")
kotlin
@RequestMapping("/user")
- 含义: 请求映射注解
- 作用 : 定义该类中所有方法的公共URL前缀为
/user
- 用法 : 类级别的路径映射,所有方法URL都会以
/user
开头
依赖注入注解
3. @Autowired
java
@Autowired
private UserMapper userMapper;
- 含义: Spring的自动注入注解
- 作用 : 根据类型自动注入
UserMapper
实例 - 用法: 用于字段、构造函数或setter方法,按类型进行依赖注入
4. @Resource
java
@Resource
private IUserService userservice;
- 含义: JSR-250标准的依赖注入注解
- 作用: 默认按名称进行依赖注入,如果未指定名称则按类型注入
- 与@Autowired区别 :
@Resource
是Java标准注解,@Autowired
是Spring特有
方法级别注解(HTTP方法映射)
5. @GetMapping
kotlin
@GetMapping("/getUserList")
- 含义: 处理HTTP GET请求的快捷注解
- 作用: 映射GET请求到特定方法
- 等价于 :
@RequestMapping(method = RequestMethod.GET)
6. @PostMapping
kotlin
@PostMapping("/addAndeditUser")
- 含义: 处理HTTP POST请求的快捷注解
- 作用: 映射POST请求到特定方法
- 用法: 通常用于创建或更新操作
参数绑定注解
7. @RequestParam
less
@RequestParam(defaultValue = "1") int currentPage
@RequestParam(required = false) Long id
-
含义: 将请求参数绑定到方法参数
-
属性:
defaultValue
: 设置参数默认值required
: 参数是否必须(默认true)
-
用法: 用于获取URL查询参数或表单参数
8. @RequestBody
sql
@RequestBody UserReqVO user
- 含义: 将请求体内容绑定到方法参数
- 作用: 用于接收JSON格式的请求数据
- 用法: 通常用于POST/PUT请求,接收复杂对象
9.@Override
typescript
@Override
public void someMethod() {
// 方法实现
}
- 含义: 表明该方法重写了父类或接口中的方法
- 作用: 编译器检查注解,确保重写正确性
- 级别: 源码级别注解(编译后不会保留)