[英]How to get Count of OneToMany field in JPA Enity?
我们如何获取 JPA 实体的OneToMany
字段的计数作为每个父实体的查询计数,而作为列表获取是昂贵的并且在 JPA 存储库中没有办法。
我想获得每个PostEntity
的点赞数和评论数。 该字段是 Lazy fetch 类型,如果我调用likes.size()
或comments.size()
那么它将从数据库加载所有评论和喜欢,并且可能有成千上万的评论和喜欢。
我知道我可以为喜欢和评论创建一个单独的存储库以获取计数,但是在从PostRepository
调用方法时如何获取每个实体的计数? 什么是最好和最有效的方法?
父实体
@Entity
@Table(name = "posts")
@Getter
@Setter
public class PostEntity extends MappedSuperClassEntity<UserEntity> {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Nullable
private String title;
@Nullable
private String postText;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="user_id")
private UserEntity user;
@Nullable
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "community_id")
private CommunityEntity community;
@OneToMany(fetch = FetchType.LAZY)
private List<CommentEntity> comments;
@OneToMany(fetch = FetchType.LAZY)
private List<LikeEntity> likes;
@Transient
private int numberOfLikes;
@Transient
private int numberOfComments;
}
我想在查询帖子列表时获取每个 PostEntity 的喜欢和评论数。 我的回购
public interface PostsRepository extends PagingAndSortingRepository<PostEntity, Integer> {
@Query(value = "SELECT P FROM PostEntity P WHERE P.user.id = :userId ORDER BY P.createdDate DESC")
Page<PostEntity> getUserPosts(int userId, Pageable pageable);
@Query(value = "select P from PostEntity P where p.community.id = :communityId order by P.createdDate desc")
Page<PostEntity> getCommunityPosts(int communityId, Pageable pageable);
}
我搜索了很多,有人建议在实体字段上使用@Formula
注释进行自定义查询,但@Formula
是特定于休眠的,不知道它是否适用于@Transient
字段。 是否有任何 JPA 特定的方法可以做到这一点,因为这是一个常见问题。
您需要带有 EXTRA 选项的“LazyCollection”注释。
@OneToMany(fetch = FetchType.LAZY)
@LazyCollection(LazyCollectionOption.EXTRA)
private List<CommentEntity> comments;
此注释将允许在不加载的情况下访问“size()”。
你可以查看这篇文章。
https://www.baeldung.com/hibernate-lazycollection
有时,我们只关心集合的属性,并不马上需要其中的对象。 例如,回到 Branch 和 Employees 示例,我们可能只需要分支中的员工数量,而不关心实际员工的实体。 在这种情况下,我们考虑使用 EXTRA 选项。 让我们更新我们的示例来处理这种情况。 与之前的情况类似,Branch 实体具有 id、name 以及与 Employee 实体的 @OneToMany 关系。 但是,我们将 @LazyCollection 的选项设置为 EXTRA:
我尝试添加评论,但由于声誉,我没有写评论的权限,所以我发送了一个答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.