我有一个用户实体:@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
提交
取消