Spring Boot 保存实体后,Sping Boot Jpa提取关系不起作用

bfrts1fy  于 2022-11-05  发布在  Spring
关注(0)|答案(2)|浏览(221)

我有一个项目与Spring Boot 和休眠。一切工作都很好地选择数据库中的数据,但我有一个问题后,插入实体。实体关系不提取后,插入。我尝试了JpaRepository saveAndFlush,但没有工作。我也尝试了findById没有工作。我该如何解决这个问题?
我的实体;

@Entity
@Table(name = "Comment")
@Data
@ApiModel(value = "Comment Model")
public class Comment {

 public static  Comment createCommentFromCommentPostRequest(CommentPostRequest commentPostRequest){
     Comment comment = new Comment();
     comment.setPostId(commentPostRequest.getPostId());
     comment.setUsersId(commentPostRequest.getUsersId());
     comment.setText(commentPostRequest.getText());
     return  comment;
 }

 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 @Column(name = "id")
 @ApiModelProperty(value = "Comment model autogenerated Id value")
 private Long id;

 @Column(name = "usersId",nullable = false)
 @ApiModelProperty(value = "User Id for describe who commented post")
 private Long usersId;

 @Column(name = "postId",nullable = false)
 @ApiModelProperty(value = "Post Id for describe which post commented")
 private Long postId;

 @Column(name = "text",length = 500)
 @ApiModelProperty(value = "define post content")
 private String text;

 @ManyToOne(fetch = FetchType.EAGER)
 @Fetch(FetchMode.JOIN)
 @JoinColumn(name = "usersId",insertable = false,updatable = false,nullable = false)
 private Users users;

 @ManyToOne(fetch = FetchType.EAGER)
 @JoinColumn(name = "postId",insertable = false,updatable = false,nullable = false)
 @JsonIgnore
 @OnDelete(action = OnDeleteAction.CASCADE)
 private Post post;
}

我的存储库;

public interface CommentRepository extends PagingAndSortingRepository<Comment,Long> {
    List<Comment> findAllByPostId(Long postId, Pageable pageable);
}

我的服务方式;

public Comment saveOneComment(CommentPostRequest commentPostRequest) {
        //TODO: implement validation
        Comment commentToSave = Comment.createCommentFromCommentPostRequest(commentPostRequest);
        commentToSave= commentRepository.save(commentToSave);
        //I tried JPA repository saveAndFlush 
        return commentRepository.findById(commentToSave.getId()).orElse(null);
    }

我的控制器;使用saveOneComment端点

@RestController
@RequestMapping("/api/comment")
@ApiOperation(value = "Comment api controller")

public class CommentController {

    CommentService commentService;

    public CommentController(CommentService commentService) {
        this.commentService = commentService;
    }

    @GetMapping("/{pageNo}/{pageSize}")
    public List<Comment> getAllComments(@PathVariable int pageNo,@PathVariable int pageSize){

        return Streamable.of(commentService.getAllComments(pageNo,pageSize)).toList();
    }

    @GetMapping("/{commentId}")
    public Comment findCommentById(@PathVariable Long commentId){
        return commentService.findById(commentId);
    }

    @GetMapping("/postId={postId}/{pageNo}/{pageSize}")
    public List<CommentResponse> getAllCommentsByPostId(@PathVariable Long postId,@PathVariable int pageNo,@PathVariable int pageSize){
        return commentService.getAllCommentsByPostIdAsCommentResponse(postId,pageNo,pageSize);
    }

    @PostMapping
    public Comment saveOneComment(@RequestBody CommentPostRequest commentPostRequest){

        return commentService.saveOneComment(commentPostRequest);
    }

    @PutMapping("/{commentId}")
    public Comment putOneComment(@PathVariable Long commentId,@RequestBody CommentPostRequest commentPostRequest){
        return commentService.putOneCommentById(commentId,commentPostRequest);
    }

    @DeleteMapping("/{commentId}")
    public void deleteOneComment(@PathVariable Long commentId){
        commentService.deleteById(commentId);
    }
}

Comment(id=32, usersId=2, postId=2, text=ddwad, users=null, post=null)插入并再次查找后,用户和帖子为空。当我运行getAllCommentsByPostId方法时,一切正常。
在插入后,仅在控制台中插入查询没有任何查询用于select语句

insert 
    into
        Comment
        (postId, text, usersId) 
    values
        (?, ?, ?)
fykwrbwg

fykwrbwg1#

我认为这里的问题是数据总是从Hibernate缓存中获取的。

return commentRepository.findById(commentToSave.getId()).orElse(null);

不过,必须有更好的方法来处理这个问题。我能想到的唯一方法是使用EntityManager.clear()EntityManager.refresh(commentToSave)
这些技术将迫使Hibernate分离托管实体并再次从数据库中获取数据。我更喜欢刷新,因为它只刷新传递的实体。
现在JPA存储库不公开实体管理器或清除/刷新方法。您必须执行CustomRepo实现来公开所有存储库上的刷新方法。
最后,您需要在保存和刷新之后调用刷新,如下所示-

public Comment saveOneComment(CommentPostRequest commentPostRequest) {
    //TODO: implement validation
    Comment commentToSave = Comment.createCommentFromCommentPostRequest(commentPostRequest);
    commentToSave= commentRepository.saveAndFlush(commentToSave); 
    commentRepository.refresh(commentToSave);
    return commentToSave;
}
qxsslcnc

qxsslcnc2#

在提交事务之后,您必须重新加载对象,我的意思是在事务之外维护关系

@PostMapping
 public Comment saveOneComment(@RequestBody CommentPostRequest commentPostRequest){

             Long id= commentService.saveOneComment(commentPostRequest);
        return commentService.loadCommentById(id);
    }
    ````

相关问题