O
O
Orkhan Hasanly2018-11-21 03:42:35
Java
Orkhan Hasanly, 2018-11-21 03:42:35

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;
}

And controller:
@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";
}

The table should look like this:
+---------+---------+
| user_id | task_id |
+---------+---------+
|       1 |       5 |
|       2 |       5 |
|       3 |       5 |
+---------+---------+

Screenshot from POST request:
5bf4a996159da438357813.jpeg
Why
@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

1 answer(s)
S
stufsdf, 2018-11-21
@stufsdf

Look, he explains well (197 lesson about @ManyToMany)
https://coursehunters.net/course/spring-i-hibernat...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question