我有一個用戶實體:@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);
添加回答
舉報
0/150
提交
取消