0

I designed a many to many relationship by using 2 OneToMany relationships as shown below:

enter image description here

In here,

  • a user must have at least one or many roles.
  • a role can be belonged no user or many users.

In this scene, is this ER diagram relations true?

And, is the Hibernate definitions also ok or any need to update?

@Entity
public class User {

     // ...

    @ManyToMany(cascade = CascadeType.MERGE)
    @JoinTable(name = "user_role",
        joinColumns = @JoinColumn(name = "user_id", nullable = false),
        inverseJoinColumns = @JoinColumn(name = "role_id")
    )
    private Set<Role> roles = new HashSet<>();

    public void addRole(Role role) {
        roles.add(role);
        role.getUsers().add(this);
    }

    public void removeRole(Role role) {
        roles.remove(role);
        role.getUsers().remove(this);
    }
}

@Entity
public class Role {
    // ...

    @ManyToMany(mappedBy = "roles")
    private Set<User> users = new HashSet<>();

    public void addUser(User user) {
        users.add(user);
        user.getRoles().add(this);
    }

    public void removeUser(User user) {
        users.remove(user);
        user.getRoles().remove(this);
    }
}
Jack
  • 1
  • 21
  • 118
  • 236

1 Answers1

1

It seems to be correct. Maybe you can use List instead of Set. Furthermore you can use CascadeType.Persist too.

For details, see https://vladmihalcea.com/the-best-way-to-use-the-manytomany-annotation-with-jpa-and-hibernate/

René Winkler
  • 6,508
  • 7
  • 42
  • 69
  • Thanks a lot, do you mean both (diagram + Hibernate implementation) are correct? – Jack Mar 05 '23 at 15:51
  • Also, I sometimes think of using Set<> or List<> in Hibernate entity relationship, but could not really understand (I read that article before, but some others also use Set<>. So, what do you think about the difference and why List<>? I am not sure if you mean for all relationship types in Hibernate or just for ManyToMany. – Jack Mar 05 '23 at 15:53