database - Twitter 喜欢 JPA 中的关系

标签 database database-design jpa

我遇到了 JPA 问题。我正在尝试实现一个允许用户关注其他用户并被关注的数据库。 我想我需要(总结)这样的东西:

USER_TABLE: id | userName
RELATIONSHIP_TABLE: id | follower | followed | acceptation

我有两个实体(也总结了):

@Entity
public class User implements Serializable {

@Id
private Long id;

private String userName;

@OneToMany
private Collection<Relationship> followings;

}


@Entity
public class Relationship implements Serializable {

@Id
private Long id;

private User follower;

private User followed;

private boolean accepted;

}

我的问题是我不确定是否可以这样做,因为我获得了比我需要的两个更多的表。

有人能帮帮我吗? 谢谢,对不起我的英语。

最佳答案

您获得了更多表,因为您没有使关联成为双向的。 JPA 无法知道 Relationship.followerUser.followings 的另一端,如果您不告诉:

@Entity
public class User implements Serializable {

    @OneToMany(mappedBy = "follower")
    private Collection<Relationship> followings;

    // ...
}


@Entity
public class Relationship implements Serializable {

    @ManyToOne
    @JoinColumn(name = "follower")
    private User follower;

    @ManyToOne
    @JoinColumn(name = "followed")
    private User followed;

    // ...
}

The documentation当然会解释它是如何工作的。

关于database - Twitter 喜欢 JPA 中的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11846433/

相关文章:

mysql - 重新排序/重置自动增量主键

ruby-on-rails - 数据库上的可序列化列的类型应为 "string"或 "text"?

php - WordPress 从主机迁移到本地服务器

sql - 带有连接表的 PostgreSQL 分区 - 查询计划中未使用分区约束

mysql - mysql数据库高效读写

java - 如何在不重新启动服务器的情况下刷新更新的实体数据

java - 无法在 JPA 图表编辑器中添加可嵌入类?

java - 谁能告诉我此查询中 spring-data 投影警告的原因吗?

mysql - 为什么以下查询会复制表数据?

sql-server - 这种情况下最好的数据库结构是什么?