英文:
Multiple different type associations between two entities - SpringBoot, PostgreSQL
问题
假设我有两个实体类,User(用户)和Post(帖子)。
如果我想要允许用户编写帖子,我会创建@OneToMany关联,以便一个用户可以拥有多篇帖子。
然后,如果我想要允许用户“关注”帖子,我会创建@ManyToMany关联,以便多个用户可以关注多篇帖子。
我的问题是:在同两个实体之间拥有这些不同类型的关联是否是一个良好的做法?如果不是,是否有更好的方法?
以下是示例代码:
@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 Long id;
@ManyToOne
@JoinColumn(name = "user_id", nullable = false)
private User user;
@ManyToMany(mappedBy = "followedPosts")
private Set<User> users;
}
英文:
Let's say I have 2 entity classes, User and 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.
If I then wanted to allow users to 'follow' posts, I would make @ManyToMany association, so that many users could follow many posts.
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;
}
答案1
得分: 3
可以,您可以在相同的两个表之间有多个关联。
一个表甚至可以在自身之间有多个关联,例如,Person
表可以有一个 father_id
列和一个 mother_id
列,它们都是指向自身的外键(一对多关联)。
英文:
Yes, you can have many associations between the same 2 tables.
A table can even have multiple associations back to itself, e.g. 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论