多种不同类型的实体之间的关联 – SpringBoot,PostgreSQL

huangapple go评论108阅读模式
英文:

Multiple different type associations between two entities - SpringBoot, PostgreSQL

问题

假设我有两个实体类,User(用户)和Post(帖子)。

如果我想要允许用户编写帖子,我会创建@OneToMany关联,以便一个用户可以拥有多篇帖子。

然后,如果我想要允许用户“关注”帖子,我会创建@ManyToMany关联,以便多个用户可以关注多篇帖子。

我的问题是:在同两个实体之间拥有这些不同类型的关联是否是一个良好的做法?如果不是,是否有更好的方法?

以下是示例代码:

  1. @Entity
  2. public class User {
  3. @Id
  4. @GeneratedValue(strategy = GenerationType.IDENTITY)
  5. private Long id;
  6. @OneToMany(mappedBy = "user")
  7. private Set<Post> posts;
  8. @ManyToMany
  9. @JoinTable(
  10. joinColumns = @JoinColumn(name = "user_id"),
  11. inverseJoinColumns = @JoinColumn(name = "post_id"))
  12. private Set<Post> followedPosts;
  13. }
  1. @Entity
  2. public class Post {
  3. @Id
  4. @GeneratedValue(strategy = GenerationType.IDENTITY)
  5. private Long id;
  6. @ManyToOne
  7. @JoinColumn(name = "user_id", nullable = false)
  8. private User user;
  9. @ManyToMany(mappedBy = "followedPosts")
  10. private Set<User> users;
  11. }
英文:

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

  1. @Entity
  2. public class User{
  3. @Id
  4. @GeneratedValue(strategy = GenerationType.IDENTITY)
  5. private Long id;
  6. @OneToMany(mappedBy = &quot;user&quot;)
  7. private Set&lt;Post&gt; posts;
  8. @ManyToMany
  9. @JoinTable(
  10. joinColumns = @JoinColumn(name = &quot;user_id&quot;),
  11. inverseJoinColumns = @JoinColumn(name = &quot;post_id&quot;))
  12. private Set&lt;Post&gt; followedPosts;
  13. }
  1. @Entity
  2. public class Post{
  3. @Id
  4. @GeneratedValue(strategy = GenerationType.IDENTITY)
  5. private Post id;
  6. @ManyToOne
  7. @JoinColumn(name = &quot;id&quot;, nullable = false)
  8. private User user;
  9. @ManyToMany(mappedBy = &quot;followedPosts&quot;)
  10. private Set&lt;User&gt; users;
  11. }

答案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.

huangapple
  • 本文由 发表于 2020年10月12日 06:48:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/64309755.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定