如何使用PostMapping正确获取具有ManyToMany关系的List <object>?

时间:2018-11-20 18:39:50

标签: spring spring-boot spring-data-jpa spring-data

开始学习spring框架(spring boot)并遇到了问题。 试图指派选定的作者来执行新创建的任务。 如何通过PostMapping获得具有List<Object>关系的@ManyToMany? 这是我的简单代码:

任务实体:

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

TaskController:

@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 |
+---------+---------+

提交表单时,将创建任务,但上面的表未填写。

浏览器“网络”标签中的屏幕截图: enter image description here

GetMapping(任务提交表单)中的这一行代码

@GetMapping("/add")
public String addTaskForm(
        Model model,
        @AuthenticationPrincipal UserDetails currentUser
) {

    User user = (User) userService.findUserByEmail(currentUser.getUsername());
    model.addAttribute("user", user);
    model.addAttribute("authors",userService.getAllUsersAuthors(user.getUser_id()));

    return "backend/add-task";
}

我在哪里错了?我需要创建一个包装器吗?提前谢谢)

2 个答案:

答案 0 :(得分:1)

您定义关系的方式,用户是关系的所有者,任务是相反的一方,因此将用户添加到任务将不会在数据库中创建任何新行。如果将“ mappedBy”移至“用户”,将JoinTable移至“任务”,则“任务”将成为关系的所有者,它将执行您想要的操作。

答案 1 :(得分:1)

两个选择:

  • 为用户配置级联类型

公共类用户{

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long user_id;

//look here bro
@ManyToMany(cascade = CascadeType.PERSIST)
@JoinTable(name = "task_authors",
        joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "user_id"),
        inverseJoinColumns = @JoinColumn(name = "task_id", referencedColumnName = "taskId")
)
private List<Task> taskList;

}

  • 交换mapledBy和@JoinTable