zBrave zBrave - 1 month ago 15
JSON Question

JSON data not include entity

I am developing a restful api.I have two entities. User and UserRole. When i send the request to api for user, it gives me

{
"id": 11,
"name": "mert",
"username": "zbrave",
"password": "$2a$10$N0eqNiuikWCy9ETQ1rdau.XEELcyEO7kukkfoiNISk/9F7gw6eB0W",
"email": "asd",
"photo": "",
"enabled": true,
"roles": [
{
"id": 1,
"role": "ADMIN"
}
],
"online": false
}


When i send the request for UserRole, it returns

[
{
"id": 1,
"role": "ADMIN"
}
]


But in UserRole entity, there is a User entity. JSON not return User entity.

public class UserRole implements Serializable {
...
@ManyToOne(targetEntity = User.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "user_id")
@JsonBackReference
private User user;
...
}



public class User implements Serializable {
...
@OneToMany(targetEntity = UserRole.class, mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JsonManagedReference
private List<UserRole> roles;
..
}


I can get the user roles from user entity's json. But not the reverse. Is there any wrong things ? Thanks for help.

Answer Source

you are using @JsonBackReference/ @JsonManagedReference so yeah that is the expected behavior , the side in the jsonBackReference wont be serialized, this is actually necessary to avoid infinite recursion since jackson will keep serializing each side of the relation from its reference in the other side, that is why you need to skip serializing one side

There is a nice solution to this, its mentioned in this link , the idea is to generate a reference to the parent entity, so if you are serializing user, you will have user->role->[reference to user instead of user], all you need to do is to annotate your entities with @JsonIdentityInfo

@JsonIdentityInfo(generator=ObjectIdGenerators.UUIDGenerator.class, property="@id")
public class UserRole implements Serializable {


@JsonIdentityInfo(generator=ObjectIdGenerators.UUIDGenerator.class, property="@id")
public class User implements Serializable {

so just do this and remove @JsonBackReference/ @JsonManagedReference