gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 09:37:14 25 4
gpt4 key购买 nike

我有一个用户实体:

@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 或 native 查询的方法实现吗?

最佳答案

我建议您使用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);

关于java - 如何通过 Spring 数据计算 OneToMany 元素的项目数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57397146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com