CrudService.java 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package com.hotent.common;
  2. import com.baomidou.mybatisplus.core.metadata.IPage;
  3. import com.hotent.base.model.CommonResult;
  4. import com.hotent.req.PageReq;
  5. import com.hotent.resp.PageResp;
  6. import javax.validation.Valid;
  7. import java.util.List;
  8. import java.util.function.Function;
  9. import java.util.function.Supplier;
  10. /**
  11. * 通用CRUD服务类
  12. * 通过组合模式实现,避免使用抽象类
  13. */
  14. public class CrudService extends PageQueryService {
  15. /**
  16. * 通用创建方法
  17. * @param createDto 创建参数
  18. * @param createFunction 创建函数
  19. * @param <T> 返回类型
  20. * @param <C> 创建参数类型
  21. * @return 创建结果
  22. */
  23. public <T, C> CommonResult<T> create(C createDto, Function<C, T> createFunction) {
  24. try {
  25. T result = createFunction.apply(createDto);
  26. return CommonResult.<T>ok().value(result).message("创建成功");
  27. } catch (Exception e) {
  28. return CommonResult.<T>error().message("创建失败:" + e.getMessage());
  29. }
  30. }
  31. /**
  32. * 通用更新方法
  33. * @param updateDto 更新参数
  34. * @param updateFunction 更新函数
  35. * @param <U> 更新参数类型
  36. * @return 更新结果
  37. */
  38. public <U> CommonResult<String> update(U updateDto, Function<U, Boolean> updateFunction) {
  39. try {
  40. boolean success = updateFunction.apply(updateDto);
  41. if (success) {
  42. return CommonResult.<String>ok().message("更新成功");
  43. } else {
  44. return CommonResult.<String>error().message("更新失败");
  45. }
  46. } catch (Exception e) {
  47. return CommonResult.<String>error().message("更新失败:" + e.getMessage());
  48. }
  49. }
  50. /**
  51. * 通用删除方法
  52. * @param id 主键
  53. * @param deleteFunction 删除函数
  54. * @return 删除结果
  55. */
  56. public CommonResult<String> delete(String id, Function<String, Boolean> deleteFunction) {
  57. try {
  58. boolean success = deleteFunction.apply(id);
  59. if (success) {
  60. return CommonResult.<String>ok().message("删除成功");
  61. } else {
  62. return CommonResult.<String>error().message("删除失败");
  63. }
  64. } catch (Exception e) {
  65. return CommonResult.<String>error().message("删除失败:" + e.getMessage());
  66. }
  67. }
  68. }