postman “status”:400,“error”:“Bad Request”,spring Boot ,创建请求

camsedfj  于 2023-06-05  发布在  Postman
关注(0)|答案(2)|浏览(588)

这是我第一次使用Spring框架,在这里我试图创建两个表类和学生,具有多对一关系,我无法创建新的学生,我尝试,我得到一个错误的请求错误400,thsi是我的学生实体

@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;
}

这是学生控制器

@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();
    }
}

get请求工作,但POST和Put请求不工作

yzckvree

yzckvree1#

首先,你可以附上你的JSON,它可以是你的JSON字段不匹配你的学生类字段。直接使用你的实体类作为你的请求负载是不好的做法->阅读更多关于DTO(域传输对象)

yhuiod9q

yhuiod9q2#

  • 在您的模型中使用@ManyToOne变量尝试以下解决方案
@JsonIgnoreProperties("students")
  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "classes_id")
  private Classes classes;

相关问题