Search code examples
springhibernatepostmany-to-manyhttp-status-code-404

Post request on table of entity having manyToMany relationship in springBoot data jpa error 404


I am trying to make a post request to my user table, the user entity having a many to many relationship to the contest entity, the contest entity featuring a many to many relationship with the team entity, but I receive error 404. Here`s the code :

User :

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "user")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private String email;

    private String password;

    private Boolean isAdmin;

    @ManyToMany
    private List<Contest> contests;


}

Contest :

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "contest")
public class Contest {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private String name;

    @ManyToMany(mappedBy = "contests")
    private List<Team> teams;

    @ManyToMany(mappedBy = "contests")
    private List<User> users;


}

Team :

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "team")
public class Team {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @ManyToMany
    private List<Contest> contests;

    private String name;

    private int wins, looses;


}

Post request JSON :

{
    "email":"john",
    "password":"bravo",
    "isAdmin":true

}

I can`t seem to make it work, before creating the relationships the rest API worked properly, so the issue is not in my repository, service, nor controller.

I tried using the JSON on top in Postman to create the post request but I get error 404, I want to be able to save new entities in my tables.


Solution

  • You should try using @JoinTable annotation, since @ManyToMany relationships need a bit more mapping, please refer to article below, it should help.

    https://www.baeldung.com/jpa-many-to-many