Why can not persist data in spring data jpa
Solution 1:
@JsonManagedReference
together with @JsonBackReference
are supposed to be used in bidirectional relationships of OneToMany
in one side and ManyToOne
on the other side, or when both sides are of type OneToOne
.
If you inspect closely the JsonBackReference Doc you will understand this
Value type of the property must be a bean: it can not be a Collection, Map, Array or enumeration. Linkage is handled such that the property annotated with this annotation is not serialized; and during deserialization, its value is set to instance that has the "managed" (forward) link.
In your case you have bidirectional ManyToMany
which means that in both sides there is a reference to a collection. So there is not a single compatible property on the side that you have @JsonBackReference
.
There are 2 solutions in your problem with ManyToMany
relationship
- Remove both
@JsonManagedReference
and@JsonBackReference
. Pick a side where you want the collection to be serialized and deserialized. Go to the other side where you don't want the other collection to be serialized and deserialized and use the annotation@JsonIgnore
. - Use custom Dtos which do not have circular dependencies and let your controller use those Dtos instead of plain entities.
Also you have another problem as well
Your controller
@RequestMapping(value = "/adduserrole", method = RequestMethod.POST)
public ResponseEntity<List<Users>> addUserRole(@RequestBody List<Users> users)
{
pojoService.addUserRole(users);
return ResponseEntity.ok(users);
}
expects as input a List of users. Not a single user. So when you want to send a single user your JSON should be
[
{
"name": "Jack",
"roles": [
{
"name": "Engineer"
},
{
"name": "Doctor"
},
{
"name": "Charter Accountant"
}
]
}
]