Home > Software design >  Insert into one table of ManytoMany and joining table hibernate
Insert into one table of ManytoMany and joining table hibernate

Time:10-20

enter image description here

Hi I am new to Hibernate and trying to build a Rest APP.

I have 3 tables in the database as shown in the above image.

USERS table has ManyToMany relation with GROUPS table and USER_GROUP is an association table.

I am using ORM, Hibernate and CurdRepository.

I am able to insert into users table and group table with save() method of CurdRepository.

Now I am trying to add a row in GROUPS table and USER_GROUP table only. Can anyone lead me to the right direction?

For example:

I want to add an groupid to GROUPS table and then associate it with an user id

Let's say I want to insert (10) groupid in GROUPS and (14,10) in USER_GROUP table.

Is it doable with ORM, if yes how?

Thanks in advance

CodePudding user response:

There are many articles online about exactly this model to showcase how to use Hibernate. Here is one article I quickly found by googling for "hibernate user group example": https://www.codejava.net/frameworks/hibernate/hibernate-many-to-many-association-annotations-example

CodePudding user response:

To use existing connecting table, USE_GROUP, User entity will be like following .

@Entity
public class Users {
    @Id
    private Integer userid;

    private String password;

    @ManyToMany(cascade = { CascadeType.MERGE, CascadeType.PERSIST })
    @JoinTable(name = "USER_GROUP", joinColumns = { @JoinColumn(name = "USERID") }, 
        inverseJoinColumns = { @JoinColumn(name = "GROUPID") })
    private Set<Groups> groups;

    // Getter, Setter
}

And then client code, add new User and Group, will be something like below.

User user = new User()
// set password , etc
Set<Groups> groups = new HashSet<>();
Group group = new Group();
// set 
groups.add(group);

user.setGroups(groups);

userRepository.save(user);
  • Related