邮差错误
控制器:
@RestController
@RequestMapping("/student_enrollment/class_subject"
公共类ClassController {
private ClassService classService;
public ClassController(ClassService classService) {
super();
this.classService = classService;
}
@PostMapping ()
public ResponseEntity<Classes> saveClass(@RequestBody Classes classes) {
return new ResponseEntity<Classes>(classService.saveClass(classes),
HttpStatus.CREATED);
}
@GetMapping
public List<Classes> getAllClasses() {
return classService.getAllClasses();
}
模型:
@ data@ entity
@Table(name = "class_subject")
公共类ClassSubject {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int subject_id;
@Column(value = "prerequisite")
private String prerequisite;
@Column(value = "max_capacity")
private int max_capacity;
}
服务impl:
@ service公共类ClassServiceImpl实现ClassService{
@Override
public ClassSubject updateClassSubject(ClassSubject classSubject, int classSubjectId) {
ClassSubject existingClassSubject = classSubjectRepository.findById(classSubjectId).orElseThrow(() -> new ResourceNotFoundException("ClassSubject", "classSubjectId", classSubjectId));
existingClassSubject.setSubject_id(classSubject.getSubject_id());
existingClassSubject.setPrerequisite(classSubject.getPrerequisite());
existingClassSubject.setMax_capacity(classSubject.getMax_capacity());
classSubjectRepository.save(existingClassSubject);
return existingClassSubject;
}
服务:
ClassService公共接口
Classes saveClass(Classes classes);
List<Classes> getAllClasses();
Classes getClassByID(int classId);
Classes updateClass(Classes classes, int classId);
void deleteClass(int classId);
}
SQL查询:
CREATE TABLE ( )subject_id INT NOT NULL,
prerequisite VARCHAR(30),
max_capacity INT NOT NULL,
PRIMARY KEY (subject_id)
);
因为在Postman中您使用的是PUT方法,而不是POST方法。
让我猜你期望'subject_id'使用数据库序列自动生成。那么你就缺少了两个注释@GeneratedValue
和@SequenceGenerator
。
因为'subject_id'不是可选字段。这就是为什么你得到错误"字段'subject_id'没有默认值"。
要创建'subject_id'字段和DB序列之间的关系,请使用以下命令:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@SequenceGenerator(name="seq",sequenceName="sequence_in_db")
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq")
private int subject_id;
你可以找到更多关于这个主题的细节。注释@Id和@GeneratedValue(strategy = GenerationType.IDENTITY)的用途是什么?为什么生成类型是identity?