I want to post a new Game to my spring boot backend from my angular application. I do this through an post from angular. This game has a relationship with my user entity in spring boot JPA. But when I do my post I get an 400 error code in the console which says:
"MethodArgumentNotValidException","fieldErrors":[{"field":"user","errorCode":"NotNull"}]}
This was the data from my post:
{category: "sport", sessieId: 20004, userID: 10004, score: null}
My game controller:
@CrossOrigin(origins = "*", allowedHeaders = "*")
@RestController
@RequestMapping(value = "/api/games", produces = MediaType.APPLICATION_JSON_VALUE)
public class GameController {
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Long createGame(@RequestBody @Valid final GameDTO gameDTO) {
return gameService.create(gameDTO);
}
// more methods for http
}
my Game domain:
@Entity
public class Game {
@Id
@Column(nullable = false, updatable = false)
@SequenceGenerator(name = "primary_sequence", sequenceName = "primary_sequence",
allocationSize = 1, initialValue = 10000)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "primary_sequence")
private Long id;
@Column(nullable = false)
private Integer sessieId;
@Column(nullable = false)
private String category;
@Column
private String score;
@ManyToOne
@JoinColumn(name = "user_id", nullable = false)
private User user;
my Game DTO:
public class GameDTO {
private Long id;
@NotNull
private Integer sessieId;
@NotNull
@Size(max = 255)
private String category;
@Size(max = 255)
private String score;
@NotNull
private Long user;
The create method from my Game service:
public Long create(final GameDTO gameDTO) {
final Game game = new Game();
mapToEntity(gameDTO, game);
return gameRepository.save(game).getId();
}
So I saw the Game entity expects a long from user, so I tried to post the object user in the post for game. the post body:
{category: "sport", sessieId: 20004,…}
category: "sport"
score: null
sessieId: 20004
user: {id: 10004, firstName: "test5", lastName: "test5", email: "test5@test.nl", password: "test"}
But then I got the following error:
JSON parse error: Cannot deserialize instance of
java.lang.Longout of START_OBJECT token;
Do I need to pass in a user object on the post? and how can I then fix the error?