Answer the question
In order to leave comments, you need to log in
How to work with ManyToMany mapping and add records using the POST method?
Hello!
There are 2 entity classes:
@Entity @Data
@Table(name = "tasks")
public class Task {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long taskId;
@ManyToMany(fetch = FetchType.EAGER, mappedBy = "taskList")
private List<User> userList;
}
@Entity @Data
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long user_id;
@ManyToMany
@JoinTable(name="task_authors",
joinColumns = @JoinColumn(name="user_id", referencedColumnName="user_id"),
inverseJoinColumns = @JoinColumn(name="task_id", referencedColumnName="taskId")
)
private List<Task> taskList;
}
@PostMapping("/add")
public String addTask(
@AuthenticationPrincipal UserDetails currentUser,
@RequestParam("WebsiteId") Website website,
@ModelAttribute Task task,
@RequestParam("taskAuthors") List<User> taskAuthors
) {
User owner = (User) userService.findUserByEmail(currentUser.getUsername());
task.setOwnerId(owner.getUser_id());
task.setUserList(taskAuthors);
taskService.addTask(task);
return "redirect:/tasks";
}
+---------+---------+
| user_id | task_id |
+---------+---------+
| 1 | 5 |
| 2 | 5 |
| 3 | 5 |
+---------+---------+
@RequestParam("taskAuthors") List<User> taskAuthors
and accordingly: task.setUserList(taskAuthors);
does not give the desired result?
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question