簡體   English   中英

如何在 JPA Enity 中獲取 OneToMany 字段的計數?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM