如何在Swift Boot的Spring Boot中基于​​请求模型的请求类型动态定义参数列表

时间:2020-10-04 21:32:55

标签: java spring spring-boot swagger swagger-2.0

我正在使用Spring Boot的Rest Controller创建休息终点。带有swagger 2的api文档。

@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的,因此需要更新。

那怎么办?

1 个答案:

答案 0 :(得分:0)

不应在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;
}
相关问题