Search code examples
sqlspring-bootone-to-manyone-to-one

How to map in Spring Boot where a Group has a one-to-one relationship to the User who created it, while also having one-to-many Users relationship?


I am really new to using Spring Boot, and at the same time, this will be my first time trying to design something like this:

Groups will be created by an instance of User. In turn this instance of Group can have zero or more members.

Groups will be created by an instance of User. In turn, this instance of Group can have zero or more members

Or maybe it looks something like this, but I hope I don't have to create two separate table of users with identical fields:

enter image description here

At the same time, is it also possible to include the group_id as a foreign key relation of Users so that I can track what group an instance of User currently belongs to, so maybe like this?

enter image description here

I am kind of doing ok with simple @ManyToOne annotations but this is my first trying to do something like this, which, if I try to summarize is as follows:

  1. A Group can be created by a User
  2. A Group can have zero or many Users under it
  3. A User instance has a relationship with which Group it currently belongs.
  4. A User can only belong to one group, while, as in number 2, a Group can have multiple members.

How should I map this? In fact, how should my ERP even look?

Thank you.


Solution

  • For the User instance who created the Group:

    @OneToOne
    private User user;
    

    For the User instances who are members of the Group:

    @JsonManagedReference
    @OneToMany
    private List<User> members;
    

    For the inverse relation of a User instance to connect it to its Group:

    @JsonBackReference
    @ManyToOne
    @JoinColumn(name = "group_id")
    private Group group;