如何通过 Spring 数据计算 OneToMany 元素的项目

我有一个用户实体:


@Entity

@Table(name = "user")

@Data

public 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 或本机查询的方法实现吗?


慕莱坞森
浏览 111回答 1
1回答

慕田峪4524236

我建议你使用 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);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java