| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- package com.hotent.common;
- import com.baomidou.mybatisplus.core.metadata.IPage;
- import com.hotent.base.model.CommonResult;
- import com.hotent.req.PageReq;
- import com.hotent.resp.PageResp;
- import javax.validation.Valid;
- import java.util.List;
- import java.util.function.Function;
- import java.util.function.Supplier;
- /**
- * 通用CRUD服务类
- * 通过组合模式实现,避免使用抽象类
- */
- public class CrudService extends PageQueryService {
-
- /**
- * 通用创建方法
- * @param createDto 创建参数
- * @param createFunction 创建函数
- * @param <T> 返回类型
- * @param <C> 创建参数类型
- * @return 创建结果
- */
- public <T, C> CommonResult<T> create(C createDto, Function<C, T> createFunction) {
- try {
- T result = createFunction.apply(createDto);
- return CommonResult.<T>ok().value(result).message("创建成功");
- } catch (Exception e) {
- return CommonResult.<T>error().message("创建失败:" + e.getMessage());
- }
- }
-
- /**
- * 通用更新方法
- * @param updateDto 更新参数
- * @param updateFunction 更新函数
- * @param <U> 更新参数类型
- * @return 更新结果
- */
- public <U> CommonResult<String> update(U updateDto, Function<U, Boolean> updateFunction) {
- try {
- boolean success = updateFunction.apply(updateDto);
- if (success) {
- return CommonResult.<String>ok().message("更新成功");
- } else {
- return CommonResult.<String>error().message("更新失败");
- }
- } catch (Exception e) {
- return CommonResult.<String>error().message("更新失败:" + e.getMessage());
- }
- }
-
- /**
- * 通用删除方法
- * @param id 主键
- * @param deleteFunction 删除函数
- * @return 删除结果
- */
- public CommonResult<String> delete(String id, Function<String, Boolean> deleteFunction) {
- try {
- boolean success = deleteFunction.apply(id);
- if (success) {
- return CommonResult.<String>ok().message("删除成功");
- } else {
- return CommonResult.<String>error().message("删除失败");
- }
- } catch (Exception e) {
- return CommonResult.<String>error().message("删除失败:" + e.getMessage());
- }
- }
- }
|