如何在swagger的spring-boot中根据请求模型的请求类型动态定义参数列表



我正在使用spring-boot的Rest Controller来创建Rest端点。以及用于api文档的swagger 2。

@RestController
@RequestMapping("/api")
public class BatchController extends ControllerConfig {
@PostMapping("/batch")
public GeneralResponse<Boolean> createBatch(@RequestBody Batch batch) throws Exception{
try{
batchService.createBatch(batch);
return new GeneralResponse<>(true,"batch created successfully", true, System.currentTimeMillis(), HttpStatus.OK);
} catch (Exception e){
return new GeneralResponse<>(false,e.getMessage(), false, System.currentTimeMillis(), HttpStatus.BAD_REQUEST);
}
}

@PutMapping("/batch")
public GeneralResponse<Boolean> updateBatch(@RequestBody Batch batch) {
try {
batchService.updateBatch(batch);
return new GeneralResponse<>(true, "batch updated successfully", true, System.currentTimeMillis(), HttpStatus.OK);
} catch (Exception e) {
return new GeneralResponse<>(false, e.getMessage(), false, System.currentTimeMillis(), HttpStatus.BAD_REQUEST);
}
}
}

批次模型:

@Entity
@Table
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Batch {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Long qualityId;
private Date date;
private String remark;
}

我正在使用JPA存储库。

现在,对于其余两个端点,Swagger将显示请求模型为:

{
id: 0,
qualityId: 0,
date: "2020-10-04T21:18:00.656Z",
remark: "string"
}

但我想隐藏";id";创建批处理请求的字段,因为它是自动生成的,但它是基于id更新所必需的。

如何做到这一点?

实体不应该在API层中公开,您应该创建一个专用的DTO类。

例如

@Data
public class PutBatchDTO {
private Long id;
private Long qualityId;
private Date date;
private String remark;
}
@Data
public class PostBatchDTO {
private Long qualityId;
private Date date;
private String remark;
}

最新更新