I have a @ManyToMany relationship table between User and Diet classes. The table (UserIsOnADiet) has 2 additional columns: fromDate (starting the diet) and toDate (ending). When a user enrolls on a diet, I want to set a value on the fromDate attribute, since it has a not-null constraint. How can I do that? Here is my code:
Class User
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer username_id;
private String username;
@ManyToMany
@JoinTable(
name = "is_on",
joinColumns = @JoinColumn(name = "username_id"),
inverseJoinColumns = @JoinColumn(name = "diet_id"))
private Set<Diet> userIsOnADiet;
Class Diet
@Entity
public class Diet {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer diet_id;
private String diet_name;
@ManyToMany(mappedBy = "userIsOnADiet")
public List<User> users;
UserService:
@Override
public User updateDiets(Integer id, Diet d) {
User u = this.findById(id);
Set<Diet> userDiets = u.getUserIsOnADiet();
userDiets.add(d);
// LocalDate fromDate = LocalDate.now();
// UserIsOnADiet userIsOnADiet = new UserIsOnADiet();
// userIsOnADiet.setFromDate(fromDate);
// I want to do something like this, but I cannot save User with null value on fromDate,
//and cannot set fromDate before creating a tuple in the database.
return this.userRepository.save(u);
}
>Solution :
You need to map your join table to an additional entity, and replace @ManyToMany association with two bidirectional @OneToMany associations.
See The best way to map a many-to-many association with extra columns when using JPA and Hibernate
For a simple many-to-many database relationship, you can use the @ManyToMany JPA annotation and, therefore, hide the join table.
However, sometimes you need more than the two Foreign Key columns in the join table, and, for this purpose, you need to replace the @ManyToMany association with two bidirectional @OneToMany associations. Unlike unidirectional @OneToMany, the bidirectional relationship is the best way to map a one-to-many database relationship that requires a collection of Child elements on the parent side