[英]Multiple different type associations between two entities - SpringBoot, PostgreSQL
Let's say I have 2 entity classes, User and Post.假设我有 2 个实体类,User 和 Post。
If I wanted to allow users to write posts, I would make @OneToMany association, so that one user can be owner of many posts.如果我想让用户写帖子,我会建立@OneToMany 关联,这样一个用户可以成为多个帖子的所有者。
If I then wanted to allow users to 'follow' posts, I would make @ManyToMany association, so that many users could follow many posts.如果我想允许用户“关注”帖子,我会建立@ManyToMany 关联,以便许多用户可以关注许多帖子。
My question: is it a good practice to have these different kind of associations between the same two entities?我的问题:在相同的两个实体之间建立这些不同类型的关联是一种好习惯吗? If not, is there a better approach?
如果没有,有没有更好的方法?
Example bellow示例如下
@Entity
public class User{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy = "user")
private Set<Post> posts;
@ManyToMany
@JoinTable(
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "post_id"))
private Set<Post> followedPosts;
}
@Entity
public class Post{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Post id;
@ManyToOne
@JoinColumn(name = "id", nullable = false)
private User user;
@ManyToMany(mappedBy = "followedPosts")
private Set<User> users;
}
Yes, you can have many associations between the same 2 tables.是的,您可以在相同的 2 个表之间有许多关联。
A table can even have multiple associations back to itself, eg a Person
table can have a father_id
column and a mother_id
column, both of them foreign keys (one-to-many associations) back to the Person
table itself.一个表甚至可以有多个关联回自身,例如,
Person
表可以有一个father_id
列和一个mother_id
列,它们都是返回到Person
表本身的外键(一对多关联)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.