I made a Spring Boot application which contains some users. These users can belong to 0, one or many groups (I omitted some lines of code for a better visualisation):
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@ManyToMany
@JoinTable(
name = "group_user",
joinColumns = {@JoinColumn(name = "user_id")},
inverseJoinColumns = {@JoinColumn(name = "group_id")}
)
private List<Group> groups = new ArrayList<>();
public User(String name, List<Group> groups) {
this.name = name;
this.groups = groups;
}
}
A group can contain 0, one or many users.
@Entity
public class Group {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@ManyToMany(mappedBy = "groups")
private List<User> users = new ArrayList<>();
public Group(String name, List<User> users) {
this.name = name;
this.users = users;
}
}
I'm using MySQL, and I have created 3 tables:
CREATE TABLE user (
id integer NOT NULL AUTO_INCREMENT,
name varchar(255),
PRIMARY KEY (id)
);
CREATE TABLE group (
id integer NOT NULL AUTO_INCREMENT,
name varchar(255),
PRIMARY KEY (id)
);
CREATE TABLE group_user (
user_id int NOT NULL,
group_id int NOT NULL,
PRIMARY KEY (user_id, group_id),
KEY group_id (group_id),
CONSTRAINT group_user_ibfk_1
FOREIGN KEY (user_id) REFERENCES user (id),
CONSTRAINT group_user_ibfk_2
FOREIGN KEY (group_id) REFERENCES group (id)
);
I managed to link an user to a group by creating this new User, passing to its constructor a group, and calling my userDao.save() method:
userDao.save(new User(name, groups));
Now I want to edit my created user and make him belong to another group. How can I do this without creating a new user?
For example, I have this user, who is in no group:
INSERT INTO user VALUES(1, 'Jordan');
And these groups:
INSERT INTO group VALUES(1, 'Group 1');
INSERT INTO group VALUES(2, 'Group 2');
Now, how can I (in Java), link my user to Group 1 and Group 2?