Issue
I can not find the way to insert data using ManyToMany in spring boot. Can anyone please suggest me how to save data using M-To-M in spring boot and hibernate.
Here down is my code.
Entity
@Entity
@Table(name = "user_master")
public class Users {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer user_id;
private String name;
@JsonManagedReference
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(name = "users_roles", joinColumns = { @JoinColumn(name = "user_id") }, inverseJoinColumns = {
@JoinColumn(name = "role_id") })
private Set<Roles> roles;
// constructor and getter/setter
}
@Entity
@Table(name = "role_master")
public class Roles {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer role_id;
private String name;
@JsonBackReference
@ManyToMany(cascade = CascadeType.ALL, mappedBy = "roles")
private Set<Users> users;
// constructor and getter/setter
}
service
@Override
public Set<Users> addAddressPerson(Set<Users> users) {
for(User user: users) {
for(Roles roles: user.getRoles()) {
roles.getUsers().add(user); // problem is in here
}
}
return users.stream().map(userRepo::save).collect(Collectors.toSet());
}
Postman
[
{
"name": "Michael",
"roles": [
{
"name": "Project Manager"
},
{
"name": "Software Developer"
}
]
}
]
Error
"message": "Cannot invoke "java.util.Set.add(Object)" because the return value of "com.rest.RestApiPojo.Entity.Roles.getUsers()" is null"
Solution
try
@Override
public Set<Users> addAddressPerson(List<Users> users) {
for(User user: users) {
for(Roles roles: user.getRoles()) {
roles.getUsers().add(user);
}
}
return users.stream().map(UserRepo::save).collect(Collectors.toSet());
}
and
@Entity
@Table(name = "user_master")
public class Users {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer user_id;
private String name;
@JsonManagedReference
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(name = "users_roles", joinColumns = { @JoinColumn(name = "user_id") }, inverseJoinColumns = {
@JoinColumn(name = "role_id") })
private Set<Roles> roles = new HashSet<>();
// constructor and getter/setter
}
@Entity
@Table(name = "role_master")
public class Roles {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer role_id;
private String name;
@JsonBackReference
@ManyToMany(cascade = CascadeType.ALL, mappedBy = "roles")
private Set<Users> users = new HashSet<>();
// constructor and getter/setter
}
Answered By - PaulD
Answer Checked By - Robin (JavaFixing Admin)