this is my first time working with spring framwork , and here i was trying to create two table classes and student , with a Many to one relationship , i can’t create new student , and i try to , i get a bad request error 400,
thsi is my student entity
@Entity
@Data
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
private String codeM;
private String firstName;
private String lastName;
@ManyToOne
private Classes classes;
}
and this is the student controller
@RestController
@RequestMapping("/student")
@AllArgsConstructor
@Slf4j
public class StudentController {
final StudentService studentService;
// create new student
@PostMapping("/")
public ResponseEntity<?> create(@RequestBody(required = false) Student student) throws Exception {
if(student == null)
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Student is null");
Student savedStudent = studentService.create(student);
return ResponseEntity.status(HttpStatus.CREATED).body(savedStudent);
}
@GetMapping("/{CodeM}")
public Student findByCodeM(@PathVariable String CodeM) throws Exception{
return studentService.findByCodeM(CodeM);
}
@PutMapping("/{CodeM}")
public ResponseEntity<?> update(@PathVariable String CodeM, @RequestBody Student student) throws Exception{
if(student == null){
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Student is null");
}
Student savedStudent = studentService.update(student);
return ResponseEntity.status(HttpStatus.OK).body(savedStudent);
}
@GetMapping("/")
public List<Student> findAll() {
return studentService.findAll();
}
}
the get Request work , but the POST and Put request Doesn’t work
2
Answers
first of all could you attach your JSON
it can be your JSON fields doesn’t match your student class fields .
and it is bad practice to use your entity class directly as your request payload -> read more about DTO (Domain Transfer Object)
Send the request parameters of JSON
Kindly share the service code
make sure your serviceLayer injection is properly connected and responded properly or not
please share the error snippt
try below solution in your Model with @ManyToOne variable