以下是一个包含增删改查接口的基类的示例代码:
public abstract class BaseController<T extends BaseEntity, S extends BaseService<T>> {
@Autowired
protected S service;
// 创建实体
@PostMapping("")
public Result create(@RequestBody T entity) {
service.save(entity);
return Result.success();
}
// 根据 ID 查询实体
@GetMapping("/{id}")
public Result getById(@PathVariable("id") Long id) {
T entity = service.getById(id);
return Result.success(entity);
}
// 更新实体
@PutMapping("/{id}")
public Result update(@PathVariable("id") Long id, @RequestBody T entity) {
entity.setId(id);
service.update(entity);
return Result.success();
}
// 删除实体
@DeleteMapping("/{id}")
public Result delete(@PathVariable("id") Long id) {
service.removeById(id);
return Result.success();
}
// 根据关键字和分页信息查询实体
@GetMapping("")
public Result query(String keyword, Integer pageNum, Integer pageSize) {
IPage<T> page = service.query(keyword, pageNum, pageSize);
return Result.success(page);
}
// 处理异常
@ExceptionHandler(Exception.class)
public Result handleException(Exception e) {
log.error("Handle exception: ", e);
return Result.failure(e.getMessage());
}
}
在这个基类中,我们定义了一些通用的方法,例如:
- create():用于创建指定类型的实体;
- getById():用于获取指定 ID 的实体;
- update():用于更新指定类型的实体;
- delete():用于删除指定 ID 的实体;
- query():用于根据关键字和分页信息查询实体;
- handleException():用于统一处理异常。
这些方法被定义为公共方法,因此可以在具体的控制器中进行继承和重写,以进行必要的定制和扩展。同时,由于这些方法被封装在基类中,因此可以减少控制器中的重复代码,提高代码的复用性和可维护性。