This is the 14th day of my participation in Gwen Challenge
It is suitable for CRUD operations of a single table. Multiple tables need to be expanded by themselves.
@Slf4j
public abstract class AbstractCoreController<T> {
private final IService<T> coreService;
public AbstractCoreController(IService<T> coreService) {
this.coreService = coreService;
}
/** * delete record */
@apiOperation (value = "delete ")
@DeleteMapping("/{id}")
public Result<T> deleteById(@PathVariable(name = "id") Serializable id) {
boolean flag = coreService.removeById(id);
if(! flag) {return Result.error();
}
return Result.ok();
}
/** * add record */
@apiOperation (value = "add ")
@PostMapping
public Result<T> insert(@RequestBody T record) {
boolean flag = coreService.save(record);
if(! flag) {return Result.error();
}
return Result.ok(record);
}
/** * Update data */
@apiOperation (value = "update ")
@PutMapping
public Result<T> updateByPrimaryKey(@RequestBody T record) {
boolean flag = coreService.updateById(record);
if(! flag) {return Result.error();
}
return Result.ok();
}
/** * query data */
@apiOperation (value = "query ")
@GetMapping("/{id}")
public Result<T> findById(@PathVariable(name = "id") Serializable id) {
T t = coreService.getById(id);
return Result.ok(t);
}
/** * query all data */
@apiOperation (value = "ApiOperation ")
@GetMapping
public Result<List<T>> findAll() {
List<T> list = coreService.list();
return Result.ok(list);
}
/** **@paramPageRequestDto General condition */
@apiOperation (value = "pagination condition ")
@PostMapping(value = "/search")
public Result<PageInfo<T>> findByPage(@RequestBody PageRequestDto<T> pageRequestDto) {
// Construct paging conditions
IPage<T> page = new Page<>(pageRequestDto.getPage(), pageRequestDto.getSize());
// Query non-LAMDA expression query conditions
QueryWrapper<T> queryWrapper = getWrapper(pageRequestDto.getBody());
// paging query
IPage<T> iPage = coreService.page(page, queryWrapper);
// Encapsulate the returned data
PageInfo<T> pageInfo = new PageInfo<>(iPage.getCurrent(), iPage.getSize(), iPage.getTotal(), iPage.getPages(), iPage.getRecords());
return Result.ok(pageInfo);
}
/** * Build the query condition * based on the body argument@paramBody Query parameter */
private QueryWrapper<T> getWrapper(T body) {
QueryWrapper<T> queryWrapper = new QueryWrapper<T>();
if (body == null) {
return queryWrapper;
}
Field[] declaredFields = body.getClass().getDeclaredFields();
for (Field declaredField : declaredFields) {
try {
// if the id annotation is encountered, the query by primary key will be skipped
//https://www.coder.work/article/2808807
if (declaredField.isAnnotationPresent(TableId.class) || "serialVersionUID".equals(declaredField.getName())) {
/ / id
continue;
}
// Property descriptor Record.getClass ()
PropertyDescriptor propDesc = new PropertyDescriptor(declaredField.getName(), body.getClass());
// Get the value of the read method object
Object value = propDesc.getReadMethod().invoke(body);
// query variable @tablefield annotation)
TableField annotation = declaredField.getAnnotation(TableField.class);
// If the value passed is null, no processing is done
if(value ! =null&& annotation ! =null) {
// If it is a string, use like
if ("java.lang.String".equals(value.getClass().getName())) {
queryWrapper.like(annotation.value(), value);
} else {
// Otherwise use the = signqueryWrapper.eq(annotation.value(), value); }}}catch(Exception e) { e.printStackTrace(); log.error(e.getCause().getLocalizedMessage()); }}returnqueryWrapper; }}Copy the code
Let your Controller inherit the abstract class and pass in the Service.
@RestController
@RequestMapping(value = "/user")
@api (value = "UserController", tags = "user management ")
public class UserController extends AbstractCoreController<User> {
private final UserService userService;
//@Autowired
public UserController(UserService userService) {
super(userService);
this.userService = userService;
}
@apiOperation (value = "get the first three users ")
@GetMapping("/three")
public Result<List<User>> getThree() {
QueryWrapper<User> userQueryWrapper = new QueryWrapper<User>();
userQueryWrapper.last("limit 3");
List<User> userList = userService.list(userQueryWrapper);
returnResult.ok(userList); }}Copy the code
There are some general packaging classes for the materials given by the teacher, which look good. Please revise and copy them for future use.
PageInfo, the generic return paging result object
@Data
@NoArgsConstructor
@AllArgsConstructor
@apiModel (description = "generic return pagination result object ", value = "result")
public class PageInfo<T> implements Serializable {
// Current page number
@APIModelProperty (notes = "current page ", Required = true)
private Long page;
// Display lines per page
@APIModelProperty (Notes = "number of items displayed per page ", Required = true)
private Long size;
// Total number of records
@APIModelProperty (Notes = "Total records ", Required = true)
private Long total;
/ / the total number of pages
@APIModelProperty (Notes = "Total pages ", Required = true)
private Long totalPages;
// Current page record
@APIModelProperty (Notes = "Response data result set ", Required = false)
private List<T> list;
}
Copy the code
PageRequestDto, page query object
@NoArgsConstructor
@AllArgsConstructor
@Data
PageRequestDto (value = "PageRequestDto")
public class PageRequestDto<T> implements Serializable {
// Current page number
@APIModelProperty (Notes = "current page number ", Required = false)
private Long page = 1L;
// Lines to display per page
@APIModelProperty (Notes = "rows per page ", Required = false)
private Long size = 10L;
// Request body entity object
@APIModelProperty (Notes = "Request body entity object ", Required = false)
private T body;
}
Copy the code
StatusCode, enumeration class StatusCode
public enum StatusCode {
// Distinguish from HTTP status codes
SUCCESS(20000."Operation successful"),
PARAM_ERROR(40000."Abnormal parameter"),
NOT_FOUND(40004."Resources do not exist"),
FAILURE(50000."System exception"),
CUSTOM_FAILURE(50001."Custom exception error");
private final Integer code;
private final String message;
StatusCode(Integer code, String message) {
this.code = code;
this.message = message;
}
// Get the status code
public Integer code(a) {
return code;
}
// Get information
public String message(a) {
return message;
}
@Override
public String toString(a) {
return String.valueOf(this.code); }}Copy the code
Result, the generic return Result object of the response
@Data
@apiModel (description = "generic return result object ", value = "result")
public class Result<T> implements Serializable {
@APIModelProperty (notes = "Error message for response result ", Required = true)
private String message;
@APIModelProperty (Notes = "Error message status code for response result,2000X indicates success,4000X indicates error, 5000X indicates server exception ", Required = true)
private Integer code;
@APIModelProperty (Notes = "Response result logical data ", Required = true)
private T data;
Success does not return data
public static <T> Result<T> ok(a) {
return new Result<T>(StatusCode.SUCCESS.message(), StatusCode.SUCCESS.code(), null);
}
// Success and return data
public static <T> Result<T> ok(T data) {
return new Result<T>(StatusCode.SUCCESS.message(), StatusCode.SUCCESS.code(), data);
}
// System error does not return data
public static <T> Result<T> error(a) {
return new Result<T>(StatusCode.FAILURE.message(), StatusCode.FAILURE.code(), null);
}
// System error and return logical data
public static <T> Result<T> error(T data) {
return new Result<T>(StatusCode.FAILURE.message(), StatusCode.FAILURE.code(), data);
}
// Error and returns the specified error message and status code as well as logical data
public static <T> Result<T> error(StatusCode statusCode, T data) {
return new Result<T>(statusCode.message(), statusCode.code(), data);
}
// Error and returns the specified error message and status code without returning data
public static <T> Result<T> error(StatusCode statusCode) {
return new Result<T>(statusCode.message(), statusCode.code(), null);
}
// Custom error and status returns
public static <T> Result<T> errorMessage(String message, Integer code, T data) {
return new Result<T>(message, code, data);
}
// The custom error message status code is fixed
public static <T> Result<T> errorMessage(String message) {
return new Result<T>(message, StatusCode.CUSTOM_FAILURE.code(), null);
}
public Result(String message, Integer code, T data) {
this.message = message;
this.code = code;
this.data = data; }}Copy the code