当客户端将数据插入sample_category表时,我得到了这个错误。这是我的控制器方法。
@PostMapping("/request")
public SampleRequest createRequest(@Valid @RequestBody SampleRequest sampleRequest) throws ResourceNotFoundException{
User user = userRepository.findById(sampleRequest.getUser().getId())
.orElseThrow(() -> new ResourceNotFoundException("User Not Found"));
Category category = categoryRepository.findById(sampleRequest.getCategory().getId())
.orElseThrow(()-> new ResourceNotFoundException("Category Not Found"));
sampleRequest.setUser(user);
sampleRequest.setCategory(category);
return sampleRequestRepository.save(sampleRequest);
}
这是模型类。
@Entity
@Table(name = "sample_requests")
public class SampleRequest extends DateAudit {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
private String title;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "user_id", nullable = false)
@OnDelete(action = OnDeleteAction.CASCADE)
private User user;
@ManyToOne(fetch = FetchType.LAZY,optional = false)
@JoinColumn(name = "category_id", nullable = false)
@OnDelete(action = OnDeleteAction.CASCADE)
private Category category;
private String description;
private Boolean approved;
@NotNull
private Long quantity;
// Getters和setter
这是客户端的请求。
{
"id" : "1",
"title" : "Test Title",
"user": {
"user" : 7
},
"category": {
"category" : 1
},
"description" : "test description",
"quantity" : "2"
}
我需要添加新的样例请求。
发布于 2020-08-15 14:05:41
在您的JSON中,您不是在id
节点中发送id
。这就是为什么用户和类别对象的id
是空的。
findById
只接受非空id,否则抛出退出(参考)。JSON应该像
{
...
"user": {
"id" : 7
},
"category": {
"id" : 1
}
}
https://stackoverflow.com/questions/63426746
复制相似问题