02. 学习SpringBoot4+JPA基本的增删改查接口
这不是噩梦,这是非常友好的提示!这是奖励!!


hutool-all
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.25</version>
</dependency>
配 JAP
# 配置 jap方言
jpa:
database-platform: org.hibernate.dialect.MySQLDialect
hibernate:
ddl-auto: none # 手动创建数据库
show-sql: true
properties:
hibernate:
# 核心配置:格式化 SQL
format_sql: true
# 高级配置:显示 SQL 里的参数(把 ? 换成实际的值)
use_sql_comments: true
新增和更新接口
/**
* 新增或者更新数据
*/
@Operation(summary = "新增管理员", description = "新增管理员对象,提供JSON对象数据")
@PostMapping("/save")
public Result save(@RequestBody Admin admin) {
adminService.save(admin);
return Result.success();
}
service
public void save(Admin admin) {
if (admin.getId() == null) { // 新增 数据库ID是自增
// 判断账户是否重复
// ExampleMatcher matcher = ExampleMatcher.matching().withStringMatcher(ExampleMatcher.StringMatcher.EXACT);
// ExampleMatcher matcher = ExampleMatcher.matching()
// .withMatcher("username", ExampleMatcher.GenericPropertyMatchers.exact());
// Example<Admin> example = Example.of(admin, matcher);
Admin dbAdmin = adminRepository.findByUsername(admin.getUsername());
if (dbAdmin != null) {
throw new CustomException("账号重复");
}
if (admin.getPassword() == null || admin.getPassword().isEmpty()) {
admin.setPassword("admin");
}
if (admin.getName() == null || admin.getName().isEmpty()) {
admin.setName("管理员");
}
admin.setRole("管理员");
} else {
Admin dbAdmin = adminRepository.findById(admin.getId()).orElse(null);
if (dbAdmin != null) {
BeanUtil.copyProperties(admin, dbAdmin, CopyOptions.create().setIgnoreNullValue(true));
admin = dbAdmin;
} else {
throw new CustomException("数据不存在");
}
}
adminRepository.save(admin);
}
删除接口
/**
* 删除数据
*/
@Operation(summary = "删除管理员", description = "删除管理员对象,根据ID删除")
@DeleteMapping("/deleteById/{id}")
public Result deleteById(@PathVariable Integer id) {
adminService.deleteById(id);
return Result.success();
}
批量删除接口
/**
* 批量删除数据
*/
@Operation(summary = "批量删除管理员", description = "批量删除管理员对象,根据ID数组删除")
@DeleteMapping("/deleteBatch")
public Result deleteBatch(@RequestBody List<Integer> ids) {
adminService.deleteBatch(ids);
return Result.success();
}
单个查询
/**
* 根据ID查询数据
*/
@Operation(summary = "查询单个管理员", description = "返回管理员")
@GetMapping("/findById/{id}")
public Result findById(@PathVariable Integer id) {
Admin admin = adminService.findById(id);
return Result.success(admin);
}
查询所有
/**
* 查询所有的数据
*/
@Operation(summary = "查询所有管理员", description = "返回管理员列表")
@GetMapping("/findAll")
public Result findAll() {
List<Admin> list = adminService.findAll();
return Result.success(list);
}
分页查询接口
/**
* 分页查询所有管理员
*/
@Operation(summary = "分页查询所有管理员", description = "返回管理员分页列表")
@GetMapping("/findPage")
public Result findPage(Admin admin,
@RequestParam(defaultValue = "1") Integer pageNum,
@RequestParam(defaultValue = "10") Integer pageSize) {
PageInfo<Admin> pageInfo = adminService.findPage(admin, pageNum, pageSize);
return Result.success(pageInfo);
}
service
public PageInfo<Admin> findPage(Admin admin, Integer pageNum, Integer pageSize) {
ExampleMatcher matcher = ExampleMatcher.matching()
.withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
.withIgnoreNullValues();
Example<Admin> example = Example.of(admin, matcher);
PageRequest pageRequest = PageRequest.of(pageNum - 1, pageSize).withSort(Sort.by(Sort.Direction.DESC, "id"));
Page<Admin> page = adminRepository.findAll(example, pageRequest);
return PageInfo.of(page);
}
分页对象 PageInfo
@Data
@Builder
public class PageInfo<T> {
private Long total;
private List<T> list;
public static <T> PageInfo<T> of(Page<T> page) {
return PageInfo.<T>builder()
.total(page.getTotalElements())
.list(page.getContent())
.build();
}
}
自定义异常 CustomException
package com.example.exception;
public class CustomException extends RuntimeException {
public CustomException(String message) {
super(message);
}
}
全局异常处理器
package com.example.exception;
import com.example.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
/**
* 处理业务异常(用户主动抛出的信息)
*/
@ExceptionHandler(CustomException.class)
public Result handleCustomException(CustomException e) {
log.error("业务异常:", e); // 打印堆栈日志方便后端排查
return Result.error("500", e.getMessage());
}
/**
* 处理所有不可知的运行时异常(如数据库报错、空指针)
*/
@ExceptionHandler(Exception.class)
public Result handleException(Exception e) {
log.error("系统异常:", e); // 打印堆栈日志方便后端排查
return Result.error("500", "系统繁忙,请稍后再试");
}
}