简体   繁体   English

如何在 JPA Enity 中获取 OneToMany 字段的计数?

[英]How to get Count of OneToMany field in JPA Enity?

How can we get the count of OneToMany field of JPA entity as querying count for each parent entity while fetching as a list is costly and there is no way in JPA Repository.我们如何获取 JPA 实体的OneToMany字段的计数作为每个父实体的查询计数,而作为列表获取是昂贵的并且在 JPA 存储库中没有办法。

I want to get the number of likes and comments for each PostEntity .我想获得每个PostEntity的点赞数和评论数。 The field is Lazy fetch type and if I call likes.size() or comments.size() then it will load all of the comments and likes from database and there can be thousands of comments and likes.该字段是 Lazy fetch 类型,如果我调用likes.size()comments.size()那么它将从数据库加载所有评论和喜欢,并且可能有成千上万的评论和喜欢。

I know I can create a seperate repo for likes and comments to get the counts but while calling method from PostRepository how to get the counts for each and every entity?我知道我可以为喜欢和评论创建一个单独的存储库以获取计数,但是在从PostRepository调用方法时如何获取每个实体的计数? What is the best and efficient way?什么是最好和最有效的方法?

Parent Entity父实体

@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;
}

I would like to get the likes and comments count for each PostEntity while querying for the list of posts.我想在查询帖子列表时获取每个 PostEntity 的喜欢和评论数。 My Repo我的回购

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);
}

I searched for a lot and someone suggested to use @Formula annotation for custom queries on the entity field but @Formula is hibernate specific and don't know if it works with @Transient field.我搜索了很多,有人建议在实体字段上使用@Formula注释进行自定义查询,但@Formula是特定于休眠的,不知道它是否适用于@Transient字段。 Is there any JPA specific way to do that as it's a common problem.是否有任何 JPA 特定的方法可以做到这一点,因为这是一个常见问题。

You need "LazyCollection" annotation with EXTRA option.您需要带有 EXTRA 选项的“LazyCollection”注释。

@OneToMany(fetch = FetchType.LAZY)
@LazyCollection(LazyCollectionOption.EXTRA)
private List<CommentEntity> comments;

This annotation would allow to access "size()" without loading.此注释将允许在不加载的情况下访问“size()”。

You can check this article.你可以查看这篇文章。

https://www.baeldung.com/hibernate-lazycollection https://www.baeldung.com/hibernate-lazycollection

Sometimes, we're only concerned with the properties of the collection, and we don't need the objects inside it right away.有时,我们只关心集合的属性,并不马上需要其中的对象。 For example, going back to the Branch and the Employees example, we could just need the number of employees in the branch while not caring about the actual employees' entities.例如,回到 Branch 和 Employees 示例,我们可能只需要分支中的员工数量,而不关心实际员工的实体。 In this case, we consider using the EXTRA option.在这种情况下,我们考虑使用 EXTRA 选项。 Let's update our example to handle this case.让我们更新我们的示例来处理这种情况。 Similar to the case before, the Branch entity has an id, name, and an @OneToMany relation with the Employee entity.与之前的情况类似,Branch 实体具有 id、name 以及与 Employee 实体的 @OneToMany 关系。 However, we set the option for @LazyCollection to be EXTRA:但是,我们将 @LazyCollection 的选项设置为 EXTRA:

I try to add comment but i have no writing comment access because of reputation so i send an answer.我尝试添加评论,但由于声誉,我没有写评论的权限,所以我发送了一个答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM