How to properly get a List with ManyToMany relationship with PostMapping?












0















Started learning the spring framework (spring boot) and ran into a problem.
Trying to assign selected authors to perform newly created task.
How to properly get a List<Object> with @ManyToMany relationship with PostMapping?
Here is my simple code:



Task entity:



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


User entity:



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


Sample table:



+---------+---------+
| user_id | task_id |
+---------+---------+
| 1 | 5 |
| 2 | 5 |
| 3 | 5 |
+---------+---------+


When submitting the form, the task is created, but the table above is not filled.



Screenshot from browsers "Network" tab:
enter image description here



This line of code from GetMapping (task submission form)



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


Where am I wrong? Do I need to create a wrapper? Thanks in advance)










share|improve this question



























    0















    Started learning the spring framework (spring boot) and ran into a problem.
    Trying to assign selected authors to perform newly created task.
    How to properly get a List<Object> with @ManyToMany relationship with PostMapping?
    Here is my simple code:



    Task entity:



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


    User entity:



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


    Sample table:



    +---------+---------+
    | user_id | task_id |
    +---------+---------+
    | 1 | 5 |
    | 2 | 5 |
    | 3 | 5 |
    +---------+---------+


    When submitting the form, the task is created, but the table above is not filled.



    Screenshot from browsers "Network" tab:
    enter image description here



    This line of code from GetMapping (task submission form)



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


    Where am I wrong? Do I need to create a wrapper? Thanks in advance)










    share|improve this question

























      0












      0








      0








      Started learning the spring framework (spring boot) and ran into a problem.
      Trying to assign selected authors to perform newly created task.
      How to properly get a List<Object> with @ManyToMany relationship with PostMapping?
      Here is my simple code:



      Task entity:



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


      User entity:



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


      Sample table:



      +---------+---------+
      | user_id | task_id |
      +---------+---------+
      | 1 | 5 |
      | 2 | 5 |
      | 3 | 5 |
      +---------+---------+


      When submitting the form, the task is created, but the table above is not filled.



      Screenshot from browsers "Network" tab:
      enter image description here



      This line of code from GetMapping (task submission form)



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


      Where am I wrong? Do I need to create a wrapper? Thanks in advance)










      share|improve this question














      Started learning the spring framework (spring boot) and ran into a problem.
      Trying to assign selected authors to perform newly created task.
      How to properly get a List<Object> with @ManyToMany relationship with PostMapping?
      Here is my simple code:



      Task entity:



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


      User entity:



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


      Sample table:



      +---------+---------+
      | user_id | task_id |
      +---------+---------+
      | 1 | 5 |
      | 2 | 5 |
      | 3 | 5 |
      +---------+---------+


      When submitting the form, the task is created, but the table above is not filled.



      Screenshot from browsers "Network" tab:
      enter image description here



      This line of code from GetMapping (task submission form)



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


      Where am I wrong? Do I need to create a wrapper? Thanks in advance)







      spring spring-boot spring-data-jpa spring-data






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 20 '18 at 18:39









      Orkhan HasanliOrkhan Hasanli

      86112




      86112
























          2 Answers
          2






          active

          oldest

          votes


















          1














          two choices:




          • config cascadeType for User


          public class User {



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


          }




          • exchange the mappedBy and @JoinTable






          share|improve this answer


























          • Thank you so much, bro! You saved my life)) Worked the 2nd variant with exchanging the mappedBy & @JoinTable.

            – Orkhan Hasanli
            Nov 21 '18 at 17:44



















          1














          the way you have defined the relations, the User is the owner of relation and Task is the inverse side so adding users to task will not create any new rows in database. If you move the "mappedBy" to User and JoinTable to Task, then Task becomes the owner of relation and it will do what you want.






          share|improve this answer
























          • Thank you so much, sir! You were right!

            – Orkhan Hasanli
            Nov 21 '18 at 17:44











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53399451%2fhow-to-properly-get-a-listobject-with-manytomany-relationship-with-postmapping%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          two choices:




          • config cascadeType for User


          public class User {



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


          }




          • exchange the mappedBy and @JoinTable






          share|improve this answer


























          • Thank you so much, bro! You saved my life)) Worked the 2nd variant with exchanging the mappedBy & @JoinTable.

            – Orkhan Hasanli
            Nov 21 '18 at 17:44
















          1














          two choices:




          • config cascadeType for User


          public class User {



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


          }




          • exchange the mappedBy and @JoinTable






          share|improve this answer


























          • Thank you so much, bro! You saved my life)) Worked the 2nd variant with exchanging the mappedBy & @JoinTable.

            – Orkhan Hasanli
            Nov 21 '18 at 17:44














          1












          1








          1







          two choices:




          • config cascadeType for User


          public class User {



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


          }




          • exchange the mappedBy and @JoinTable






          share|improve this answer















          two choices:




          • config cascadeType for User


          public class User {



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


          }




          • exchange the mappedBy and @JoinTable







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 21 '18 at 3:45

























          answered Nov 21 '18 at 3:38









          AokoQinAokoQin

          794




          794













          • Thank you so much, bro! You saved my life)) Worked the 2nd variant with exchanging the mappedBy & @JoinTable.

            – Orkhan Hasanli
            Nov 21 '18 at 17:44



















          • Thank you so much, bro! You saved my life)) Worked the 2nd variant with exchanging the mappedBy & @JoinTable.

            – Orkhan Hasanli
            Nov 21 '18 at 17:44

















          Thank you so much, bro! You saved my life)) Worked the 2nd variant with exchanging the mappedBy & @JoinTable.

          – Orkhan Hasanli
          Nov 21 '18 at 17:44





          Thank you so much, bro! You saved my life)) Worked the 2nd variant with exchanging the mappedBy & @JoinTable.

          – Orkhan Hasanli
          Nov 21 '18 at 17:44













          1














          the way you have defined the relations, the User is the owner of relation and Task is the inverse side so adding users to task will not create any new rows in database. If you move the "mappedBy" to User and JoinTable to Task, then Task becomes the owner of relation and it will do what you want.






          share|improve this answer
























          • Thank you so much, sir! You were right!

            – Orkhan Hasanli
            Nov 21 '18 at 17:44
















          1














          the way you have defined the relations, the User is the owner of relation and Task is the inverse side so adding users to task will not create any new rows in database. If you move the "mappedBy" to User and JoinTable to Task, then Task becomes the owner of relation and it will do what you want.






          share|improve this answer
























          • Thank you so much, sir! You were right!

            – Orkhan Hasanli
            Nov 21 '18 at 17:44














          1












          1








          1







          the way you have defined the relations, the User is the owner of relation and Task is the inverse side so adding users to task will not create any new rows in database. If you move the "mappedBy" to User and JoinTable to Task, then Task becomes the owner of relation and it will do what you want.






          share|improve this answer













          the way you have defined the relations, the User is the owner of relation and Task is the inverse side so adding users to task will not create any new rows in database. If you move the "mappedBy" to User and JoinTable to Task, then Task becomes the owner of relation and it will do what you want.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 21 '18 at 2:27









          Reza NasiriReza Nasiri

          525115




          525115













          • Thank you so much, sir! You were right!

            – Orkhan Hasanli
            Nov 21 '18 at 17:44



















          • Thank you so much, sir! You were right!

            – Orkhan Hasanli
            Nov 21 '18 at 17:44

















          Thank you so much, sir! You were right!

          – Orkhan Hasanli
          Nov 21 '18 at 17:44





          Thank you so much, sir! You were right!

          – Orkhan Hasanli
          Nov 21 '18 at 17:44


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53399451%2fhow-to-properly-get-a-listobject-with-manytomany-relationship-with-postmapping%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          MongoDB - Not Authorized To Execute Command

          How to fix TextFormField cause rebuild widget in Flutter

          Npm cannot find a required file even through it is in the searched directory