I am using Spring Boot for backend in my project. In the database (MySQL) I have a many-to-many relationship which has the next entities: User, interest and relUserInterest. The RelUserInterest is a intermediate table between User and Interest and has extra columns.
User Entity
@Entity
public class User {
@Id @GeneratedValue private Long id;
@NotNull
@Column (unique = true) private String email;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
@NotNull
Set<RelUserInterest> priority = new HashSet<>();
// more attributes, constructor, get and set
}
Interest entity
@Entity
public class Interest {
@Id
@GeneratedValue
private long id;
@NotEmpty
@Column(unique = true)
private String nameInterest;
@OneToMany(mappedBy = "interest", cascade = CascadeType.ALL)
@NotNull
Set<RelUserInterest> priority = new HashSet<>();
// more attributes, constructor, get and set
}
RelUserInterest entity
@Entity
@Table(name = "rel_user_interest")
@IdClass(UserInterestId.class)
public class RelUserInterest implements Serializable {
@Id
@ManyToOne
@JoinColumn(name = "user_id", referencedColumnName = "id")
User user;
@Id
@ManyToOne
@JoinColumn(name = "interest_id", referencedColumnName = "id")
Interest interest;
int priority;
// constructor, get and set
}
So far so good. I want to update the user and their interests. My controller is this. I want to do is when I update a existing user, update the intermediate table (RelUserInterest).
@PutMapping("/update/{id}")
public ResponseEntity<?> updateUser(@Validated @RequestBody UserDTOUpdate userDTOUpdate, BindingResult result, @PathVariable Long id) {
// More code
User user = usersService.getUserById(id);
// Code updating other attributes
// Here this the problem --> I don't know how to update the attribute priority of RelUserInterest
usersService.updateUser(user);
return new ResponseEntity<>(new Mensaje("Usuario actualizado"), HttpStatus.CREATED);
}
I have found several links but I'm not sure which is the best solution and I don't know how do it with my code.
- How to update ManyToMany with extra columns
- Spring boot JPA many to many with extra column insert and update issue
- Spring-Data-JPA ManyToMany relationship with extra column
In the Postman i want to send the next JSON although the interest array can be different if it is necessary for the solution:
{
"age": 22,
"genre": "Male",
"userName": "Miguel",
"roles": [
"ROLE_ADMIN",
"ROLE_USER"
],
"interest": [
{
"interestID": 1,
"nameInterest": "Museum",
"priority": 9
}
]
}
Question
So, the question is: How can I update the attribute priority of the RelUserEntity table? I suppose that making an intermediate table repository is a mistake. I'm a little lost. I hope you can help me. Thank you.