Spring Boot使用@OneToMany关联保存时报not-null property错误如何解决?
Spring JPA @OneToMany关联保存报错解决方案
错误根因
你当前使用的是双向@OneToMany关联,Post实体中@OneToMany注解配置的mappedBy = "post"表示:关联关系的维护方为Comment实体的post属性,只有维护方设置的关联值才会被Hibernate同步到数据库。
JSON反序列化后仅给Post的comments集合赋值了所有评论对象,所有Comment实例的post属性均为null,而Comment实体的post字段配置了optional = false、对应表字段post_id配置了nullable = false,因此保存时触发非空约束报错。
解决方案
方案1:直接修改Controller保存逻辑(快速生效)
在保存Post前遍历所有关联的Comment,手动为其设置关联的Post对象即可:
// PostController.java 调整createPost方法 @PostMapping("/posts") public Post createPost(@Valid @RequestBody Post post) { if (post.getComments() != null) { post.getComments().forEach(comment -> comment.setPost(post)); } return postRepository.save(post); }
方案2:实体层增加关联维护方法(更符合JPA规范)
在Post实体中新增辅助方法统一维护双向关联,避免业务代码重复编写关联逻辑:
// Post.java 新增关联维护方法 public void addComment(Comment comment) { this.comments.add(comment); comment.setPost(this); } public void removeComment(Comment comment) { this.comments.remove(comment); comment.setPost(null); }
调整Controller逻辑调用辅助方法:
// PostController.java @PostMapping("/posts") public Post createPost(@Valid @RequestBody Post post) { if (post.getComments() != null) { Set<Comment> receiveComments = post.getComments(); post.setComments(new HashSet<>()); receiveComments.forEach(post::addComment); } return postRepository.save(post); }
可选方案:改为单向一对多(仅适合无需从Comment查询所属Post的场景)
如果业务中不存在通过Comment查询关联Post的需求,可以将双向关联改为单向关联,无需维护Comment端的post属性:
// Post.java 修改@OneToMany配置,删除mappedBy,新增@JoinColumn @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinColumn(name = "post_id") private Set<Comment> comments = new HashSet<>(); // Comment.java 删除private Post post属性及对应的get/set方法
内容的提问来源于stack exchange,提问作者Seeschon
相关产品推荐
相关产品推荐

