Spring Boot中PostMapping传一对多关系对象:仅传用户ID创建评论
解决Spring Boot中通过userId创建Comment的问题
你当前的代码无法直接通过传入writer_id创建Comment,原因是请求中的writer_id是Long类型,而Comment实体里的writer是User对象,Jackson无法自动完成这种转换。下面提供两种可行的解决方法:
方案一:使用DTO(推荐)
创建专门接收请求参数的DTO类,分离请求数据和数据库实体,更符合分层架构设计:
1. 定义CommentDTO
public class CommentDTO { private String message; private Long writer_id; // 生成getter和setter方法 }
2. 修改CommentController
让Controller接收DTO而非Comment实体:
@PostMapping public void createComment(@RequestBody CommentDTO commentDTO) { commentService.createComment(commentDTO); }
3. 修改CommentService
通过userId查询User实体,组装Comment对象后保存:
public void createComment(CommentDTO commentDTO) { // 根据userId查询用户,不存在则抛出异常 User writer = userRepository.findById(commentDTO.getWriter_id()) .orElseThrow(() -> new UserNotFoundException("Writer does not exist")); // 组装Comment对象 Comment comment = new Comment(); comment.setMessage(commentDTO.getMessage()); comment.setWriter(writer); // 保存到数据库 commentRepository.save(comment); }
方案二:临时字段映射(不推荐)
如果不想新增DTO类,可以在Comment实体中添加一个不映射到数据库的临时字段来接收writer_id:
1. 修改Comment实体
@Entity @Table(name="tbl_comments") public class Comment { // 原有属性和方法... // 临时字段,不映射到数据库 @Transient private Long writer_id; // 生成writer_id的getter和setter方法 }
2. 修改CommentService
在保存前通过临时字段查询User并关联:
public void createComment(Comment comment) { User writer = userRepository.findById(comment.getWriter_id()) .orElseThrow(() -> new UserNotFoundException("Writer does not exist")); comment.setWriter(writer); commentRepository.save(comment); }
注意:这种方法会污染实体类的职责,实体类应专注于数据库映射逻辑,因此更推荐使用DTO方案。
内容的提问来源于stack exchange,提问作者Leon
相关产品推荐
相关产品推荐

