亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何通過 Spring 數據計算 OneToMany 元素的項目

如何通過 Spring 數據計算 OneToMany 元素的項目

慕萊塢森 2023-05-24 15:32:44
我有一個用戶實體:@Entity@Table(name = "user")@Datapublic class UserEntity extends BaseEntity {    @Column(name = "full_name")    private String fullName;    ....    @OneToMany(cascade = CascadeType.REMOVE)    @JoinTable(name = "user_post",            joinColumns = {@JoinColumn(name = "user_id")},            inverseJoinColumns = {@JoinColumn(name = "post_id")})    private Set<PostEntity> posts;    @ManyToMany    @JoinTable(name = "user_followers",            joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},            inverseJoinColumns = {@JoinColumn(name = "follower_id", referencedColumnName = "id")})    private Set<UserEntity> followers = new HashSet<>();    @ManyToMany    @JoinTable(name = "user_followings",            joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},            inverseJoinColumns = {@JoinColumn(name = "following_id", referencedColumnName = "id")})    private Set<UserEntity> followings = new HashSet<>();}現在我想計算一個用戶的關注者。我可以獲得關注者列表并使用 list.size() 但這并不好。我只想計算它們而不是整個對象。這可以通過我的 UserRepostiory 中擴展 JpaRepostiory 或本機查詢的方法實現嗎?
查看完整描述

1 回答

?
慕田峪4524236

TA貢獻1875條經驗 獲得超5個贊

我建議你使用 JPQL 語法。在UserRepository你可以添加計數方法。請嘗試 :


@Query("select count(p) from User u join u.posts p where u.id = ?1")

long countPosts(Long id);


@Query("select count(f) from User u join u.followers f where u.id = ?1")

long countFollowers(Long id);


@Query("select count(f) from User u join u.followings f where u.id = ?1")

long countFollowings(Long id);


查看完整回答
反對 回復 2023-05-24
  • 1 回答
  • 0 關注
  • 136 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號