Reputation: 1
I am trying to make a post request using POSTMAN with Spring Boot
The relation between User and Role is (ManyToOne).
Why does role returns this: ("role":null)
POSTMAN VIEW: {
"name": "usertest",
"lastname": "usertest",
"email": "[email protected]",
"role": {
"id": 1
}
}
POSTMAN OUTPUT:
{
"id": 29,
"name": "usertest",
"lastname": "usertest",
"email": "[email protected]",
"role": {
"id": 1,
"role": null
}
}
CONTROLLER:
@PostMapping("user")
public ResponseEntity<User> addUser(@RequestBody User user){
try {
userService.save(user);
HttpHeaders httpHeaders = new HttpHeaders();
return ResponseEntity.status(HttpStatus.CREATED)
.headers(httpHeaders)
.body(user);
}
catch (Exception e){
e.printStackTrace();
return null;
}
}
ENTITY USER:
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(nullable = false, updatable = false)
private Role role;
Upvotes: 0
Views: 3405
Reputation: 12375
You are mapping the input request body to a User object and persisting it into DB by calling userService.save(user)
and you are NOT re-initializing user
property with the persisted entity reference. So, it is a plain POJO, not a JPA managed entity. That's why the "role" property is still null.
You could return the persistent user from userService.save(user)
method and return that from the Controller method. Also. you need to take care of loading Role inside User as it is a LAZY property.
Upvotes: 1