gpt4 book ai didi

java - OneToMany 映射在 Controller CRUD Spring Boot Rest API 中不起作用

转载 作者:行者123 更新时间:2023-12-02 10:34:17 24 4
gpt4 key购买 nike

我不知道如何解决api的500状态响应。我正在使用 Postman 进行测试。

请求

{
"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@ManyToOneentity state transitions应该从父实体传播到子实体。

@ManyToOne side 始终是 Child 关联,因为它应该映射底层 FK。

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

关于java - OneToMany 映射在 Controller CRUD Spring Boot Rest API 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53404082/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com