简体   繁体   中英

Multiple different type associations between two entities - SpringBoot, PostgreSQL

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;
}

Yes, you can have many associations between the same 2 tables.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM