我不知道如何通过api解决500状态响应。我正在与邮递员进行测试。

要求

{
        "nome": "Ciencia da Computação",
        "totalCreditos": 2333,
        "professor": {
            "id": 2,
            "matricula": 0,
            "nome": "José da silva"
    }
}


如何实现一对多关系并以正确的方式公开API以进行CRUD操作。
我遇到500错误。
我不知道是否需要更改Controller功能

CursoController.java

@CrossOrigin(origins = "*")
@RestController
@RequestMapping({"/api/curso"})
public class CursoController {
    @Autowired
    private CursoService cursoService;
    private ProfessorService professorService;

    @PostMapping
    public Curso create(@RequestBody Curso curso){
        return cursoService.create(curso);
    }

    @GetMapping(path = {"/{id}"})
    public Curso findOne(@PathVariable("id") int id){
        return cursoService.findById(id);
    }

    @PutMapping
    public Curso update(@RequestBody Curso Curso){
        return cursoService.update(Curso);
    }

    @DeleteMapping(path ={"/{id}"})
    public Curso delete(@PathVariable("id") int id) {
        return cursoService.delete(id);
    }

    @GetMapping
    public List findAll(){
        return cursoService.findAll();
    }
}


Curso.java

@Entity
@Table(name = "curso")
public class Curso implements Serializable {
    @Id
    @Column
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    @Column
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long codigo;
    @Column
    private Long totalCreditos;

    @Column
    private String nome;

    @ManyToOne(fetch = FetchType.LAZY, optional = false, cascade =
    CascadeType.PERSIST)
    @JoinColumn(name = "professor_id", nullable = false)
    @OnDelete(action = OnDeleteAction.CASCADE)
    @JsonIgnore
    @JsonManagedReference
    private Professor professor;


}

最佳答案

您永远不要在@ManyToOne上使用CascadeType.ALL,因为实体状态转换应从父实体传播到子实体。

去掉

(fetch = FetchType.LAZY, optional = false, cascade =
    CascadeType.PERSIST)




@ManyToOne(fetch = FetchType.LAZY, optional = false, cascade =
    CascadeType.PERSIST)


并添加到

 @OneToMany(fetch = FetchType.LAZY, optional = false, cascade =
        CascadeType.PERSIST)


侧。

说明:

正如vladmihalcea在this article和他的书High-Performance Java Persistence中所述,您永远不要在CascadeType.ALL上使用@ManyToOne,因为entity state transitions应该从父级实体传播到子级实体。

@ManyToOne始终是Child关联,因为它应映射基础FK。

因此,将CascadeType.ALL@ManyToOne关联移动到@OneToMany,由于它是the most efficient one-to-many mapping,因此应使用mappedBy属性。
`

10-08 13:21