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

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

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 = &quot;user&quot;)
    private Set&lt;Post&gt; posts;

    @ManyToMany
    @JoinTable(
            joinColumns = @JoinColumn(name = &quot;user_id&quot;),
            inverseJoinColumns = @JoinColumn(name = &quot;post_id&quot;))
    private Set&lt;Post&gt; followedPosts;
}
@Entity
public class Post{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Post id;

    @ManyToOne
    @JoinColumn(name = &quot;id&quot;, nullable = false)
    private User user;

    @ManyToMany(mappedBy = &quot;followedPosts&quot;)
    private Set&lt;User&gt; 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.

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:

确定