title: How to send POST request with Many to many relationship in Spring Boot
body: <p>Anyone have any ideas on how I could do postmapping for the Many-to-Many relationship? Getting the data works, but this is what I'm having trouble with</p>
  <p>I tried using the &quot;guide&quot; but unfortunately I don't understand it very well yet</p>
  <p>Here is my entities:</p>
  <p>Album</p>
  <pre><code>@Entity
  public class Album implements Serializable {
  @Id
  @GeneratedValue(strategy=GenerationType.IDENTITY)
  Long id;
  String name;
  String artist;
  String cover;
  @ManyToMany(fetch = FetchType.LAZY,  cascade =
          {
                  CascadeType.DETACH,
                  CascadeType.MERGE,
                  CascadeType.REFRESH,
                  CascadeType.PERSIST
          })
  @JoinTable( name = &quot;user_albums&quot;,
          joinColumns = @JoinColumn(name = &quot;album_id&quot;, nullable = false),
          inverseJoinColumns = @JoinColumn(name = &quot;user_id&quot;, nullable = false)
         )
  @JsonBackReference
  
  @OnDelete(action = OnDeleteAction.CASCADE)
  private Set&lt;User&gt; users = new HashSet&lt;&gt;();
  </code></pre>
  <p>User:</p>
  <pre><code> @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
  @NotBlank
  @Size(max = 20)
  private String username;
  @NotBlank
  @Size(max = 50)
  @Email
  private String email;
  @NotBlank
  @Size(max = 120)
  private String password;
  
  
  @ManyToMany(fetch = FetchType.LAZY,  cascade =
          {
                  CascadeType.DETACH,
                  CascadeType.MERGE,
                  CascadeType.REFRESH,
                  CascadeType.PERSIST
          })
  @JoinTable( name = &quot;user_albums&quot;,
          joinColumns = @JoinColumn(name = &quot;user_id&quot;, nullable = false),
          inverseJoinColumns = @JoinColumn(name = &quot;album_id&quot;, nullable = false)
  )
  
  
  @OnDelete(action = OnDeleteAction.CASCADE)
  private Set&lt;Album&gt; albums = new HashSet&lt;&gt;();
  </code></pre>
  <p>I tried it this way but it didn't work</p>
  <pre><code>@PostMapping(&quot;/users/mal/{userId}/album&quot;)
  public ResponseEntity&lt;Album&gt; addAlbum(@PathVariable(value = &quot;userId&quot;) Long userId, @RequestBody Album albumRequest, User userRequest) {
      Album newMal = userRepo.findById(userId).map(user -&gt; {
          long albumId = userRequest.getId();
  
          user.addAlbum(albumRequest);
          return albumRepo.save(albumRequest);
      }).orElseThrow(() -&gt; new RuntimeException(&quot;Not found USER with id = &quot; + userId));
      return new ResponseEntity&lt;&gt;(newMal, HttpStatus.CREATED);
  </code></pre>