Reputation: 334
I have two classes:
Person.java:
@Entity
@PrimaryKeyJoinColumn(name="owner_id")
public class Person extends Owner {
@ManyToOne
@JoinColumn(name = "car_sharing_id")
@JsonBackReference
private CarSharing carSharing;
}
CarSharing.java:
@Entity
public class CarSharing extends MetadataEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToOne
@JoinColumn(name = "owner_id", nullable = false)
@NotNull
private Person owner;
@OneToMany(mappedBy = "carSharing", cascade = CascadeType.ALL)
@Valid
private Set<Person> members;
}
I am using @JsonBackReference
to avoid infinite cycles. The CarSharing
class is working fine the problem only happens to the Person
class.
Getting the person seems to ignore the carSharing
property. As it is null
when coming back to the server the update is unlinking the reference to the carsharing_id
in the person
table.
Stopping the loop is fine but i would also need the carSharing
available in the Person
class.
Any idea how to solve this?
Upvotes: 2
Views: 1972
Reputation: 4724
If you are using Jackson 2.x, you can use the Annotation @JsonIdentityInfo
:
Whether Object Identity information is to be used for determining how to serialize/deserialize property value to/from JSON (and other data formats) will be based on existence (or lack thereof) of @JsonIdentityInfo annotation.
see: http://wiki.fasterxml.com/JacksonFeatureObjectIdentity
For example, if you annotate the class CarSharing
:
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
//...
@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id")
public class CarSharing {
the JSON result of a person (I added a field name to this class) is:
{
"carSharing": {
"@id": 1,
"id": 12345,
"owner": {
"carSharing": 1,
"name": "owner"
},
"members": [
{
"carSharing": 1,
"name": "owner"
},
{
"carSharing": 1,
"name": "driver2"
},
{
"carSharing": 1,
"name": "driver"
}
]
},
"name": "driver2"
}
And a CarSharing instance with id=12345
:
{
"@id": 1,
"id": 12345,
"owner": {
"carSharing": 1,
"name": "owner"
},
"members": [
{
"carSharing": 1,
"name": "owner"
},
{
"carSharing": 1,
"name": "driver2"
},
{
"carSharing": 1,
"name": "driver"
}
]
}
The field @id
is generated from jackson. If the referenced object is not serialized, the value is set to the @id
of the referenced object.
Upvotes: 1