我正在尝试执行 POST 请求以将子项(章节)保存到父项(User
)上,但它不起作用。
所有其他请求都工作正常。 PostMapping
Controller 将 Body
保存到数据库中,但不保存父关系(在我的例子中,类 Chapter → user_id = null
)。
我在 Postman 中使用以下 URL:
http://localhost:8080/api/chapters?username=admin
Content-type: application/json
Body: raw
有了这个 body :
{
"name": "Product Development",
}
Username: "admin" with Id= 1
<小时/>
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(nullable = false, updatable = false)
private Long id;
@Column(nullable = false, unique = true)
private String username;
@Column(nullable = false)
private String password;
@Column(nullable = false)
private String role;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "user")
private Set<Chapter> chapters = new HashSet<>();
public void addChapter(Chapter chapter) {
this.chapters.add(chapter);
chapter.setUser(this);
}
....
}
@Entity
public class Chapter {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(nullable = false, updatable = false)
private Long id;
private String name;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
....
}
@RestController
public class ChapterController {
@Autowired
private ChapterRepository chapterRepository;
@Autowired
private UserRepository userRepository;
@RequestMapping("/chapters")
public Iterable<Chapter> getChapter() {
return chapterRepository.findAll();
}
@RequestMapping(value="/users/{id}/chapters", method = RequestMethod.GET)
Chapter getChapter(@PathVariable (value = "id") Long id) {
return chapterRepository.findByUserId(id).get();
}
@PostMapping("/chapters")// issue is here
void newChapter(@RequestParam (value = "username", required=true)
String username, @RequestBody Chapter newChapter) {
User user = userRepository.findByUsername(username);
user.addChapter(newChapter);
System.out.println(user);
userRepository.save(user);
}
}
我希望将子级与父级一起保存,这意味着 user_id = 1
因为目前只有一个用户 (id = 1
)。我错过了什么?
最佳答案
您必须为 @ManyToOne
映射添加级联。
在您的用户 @Entity
中更新此行,它将起作用:
@Entity
public class Chapter {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(nullable = false, updatable = false)
private Long id;
private String name;
@ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
@JoinColumn(name = "user_id")
private User user;
}
您可能想做的第二件事是更新您的 Controller ,因此它将用户 ID 分配给您的新章节,就像这样:
@PostMapping("/chapters")// issue is here
void newChapter(@RequestParam (value = "username", required=true)
String username, @RequestBody Chapter newChapter) {
User user = userRepository.findByUsername(username);
newChapter.setUser(user);
user.addChapter(newChapter);
System.out.println(user);
userRepository.save(user);
}
关于java - 在执行 POST 请求时,如何将子项保存在现有父项中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57697899/