gpt4 book ai didi

java - 正确使用单个 @ManyToOne 关联进行大小控制和分页

转载 作者:行者123 更新时间:2023-12-02 01:59:41 25 4
gpt4 key购买 nike

我想避免“双向 @OneToMany”关联,因为:

  1. 它无法限制 @OneToMany 的大小
  2. 我需要进行分页。

为此我使用了 this tutorial其中描述了“Just @ManyToOne”关联,但不幸的是,它只给出了与此相关的一行代码:

List<PostComment> comments = entityManager.createQuery(
"select pc " +
"from PostComment pc " +
"where pc.post.id = :postId", PostComment.class)
.setParameter( "postId", 1L )
.getResultList();

所以,我有很多问题:

  1. 我到底应该在哪里使用这条线?

  2. 我应该如何以及在哪里获取 EntityManager?就在实体中吗?这是一个好的解决方案吗?

  3. 如何避免使用 EntityManager?我已经看过this和其他问题,但不幸的是他们没有帮助我。

  4. 我将 Post 作为父实体,将 Comment 作为子实体。一篇帖子可以有很多评论。代码:

如果我在评论中使用它:

@ManyToOne(fetch = FetchType.LAZY)   
@JoinColumn(name = "post_id")
private Post post;

帖子中的内容:

private Set<Comment> comments; 

所以,我删除了 @OneToMany 正如上面提到的教程所说,我得到了:

MappingException: Could not determine type for: java.util.List, at table: post, for columns: [org.hibernate.mapping.Column(comments)]

那么,我如何使用“Just @ManyToOne”关联(或其他方便的东西)来控制评论的大小和分页?

最佳答案

我发现对我来说并不完美,但最正确的解决方案。

帖子:

@Entity(name = "Post")
public class Post {

//...
@Transient
private List<PostComment> comments;

public void addComment(PostComment comment) {
comments.add(comment);
comment.setPost(this);
}

public void removeComment(PostComment comment) {
comments.remove(comment);
comment.setPost(null);
}

public void clearComments(){
comments.clear();
}

public List<PostComment> getComments() {
return comments;
}

public void setComments(List<PostComment> comments) {
this.comments = comments;
}
}

发表评论:

@Entity(name = "PostComment")
public class PostComment {

//...

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "post_id")
private Post post;

public Post getPost() {
return post;
}

public void setPost(Post post) {
this.post = post;
}
}

PostCommentServiceImpl:

@Service
public class PostCommentServiceImpl {

@Autowired
private PostCommentRepository repository;

//...

public void setCommentsInPost(Post post, int first, int size){
Pageable pageRequest = new PageRequest(first, size);

Page<PostComment> pageOfPostComment = repository.findByPostId(post.getId(), pageRequest);

post.setComments(pageOfPostComment.getContent());
}
}

Controller :

@Controller
public class PostController {
@Autowired
private PostCommentService postCommentService;

@Autowired
private PostService postService;

//...
@RequestMapping(value = "/something", method = RequestMethod.GET)
public void foo() {
Post post = postService.findById(1L);

postCommentService.setCommentsInPost(post,0,10);

//...
}
//...
}

关于java - 正确使用单个 @ManyToOne 关联进行大小控制和分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51774594/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com