当我用 @Entity
获取 User
注释时,我试图提取"mutual friends"的计数,最好不必迭代所有分页结果并查询适当的值 .
这意味着对于任何给定的用户,结果可能会有所不同,具体取决于谁正在读取数据库 . 基本上是以下查询:
select count(friendship) from Friendship friendship where
friendship.owner.id = user_id and friendship.friend in
(SELECT f.friend FROM Friendship f where f.owner.id = current_user_id)
其中 user_id 是被选中的用户,并且 current_user_id 已登录用户 .
应该比较的用户是Spring Security定义的 Principle
和SpEL格式: ?#{principle}
我found out是 @Formula
是休眠而且不适用SpEL,所以我必须使用 @Query
.
我想不出一种有效的方法,除了可能定义一个新的数据库表(我正在使用Postgresql)并在更新友谊时更新它 .
这是我的友谊实体的基本面貌:
@Entity
@Table(name = "friendship")
public class Friendship {
@Id
private Long id;
@ManyToOne
@JoinColumn(name="owner_id", referencedColumnName = "id", nullable = false, updatable = false)
private User owner;
@ManyToOne
@JoinColumn(name="friend_id", referencedColumnName = "id", nullable = false, updatable = false)
private User friend;
每个新的“友谊”都会创建其中两个记录,因此我可以轻松查询任何用户的好友列表 .