问题描述
我正在使用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,HttpStatus.BAD_REQUEST);
}
}
@PutMapping("/batch")
public GeneralResponse<Boolean> updateBatch(@RequestBody Batch batch) {
try {
batchService.updateBatch(batch);
return new GeneralResponse<>(true,"batch updated successfully",HttpStatus.OK);
} catch (Exception e) {
return new GeneralResponse<>(false,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;
}