Reputation: 368
in official documentation I have read that jsonbackreference cannot be applied for collection
Value type of the property must be a bean: it can not be a Collection, Map, Array or enumeration.
but is is working on my machine for collection does anybody know why?
And by the way I found in tutorial that they are using it for collection.
Upvotes: 4
Views: 847
Reputation: 95
Well the tutorial which you have linked stated that: We can switch around the @JsonManaged and @JsonbackReference annotations when we are trying to do the serialization.
But when we try to do the same when we try to do the deserialization then hibernate is gonna throw an exception.
Something like this:
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot handle managed/back reference 'defaultReference': back reference type (java.util.List<io.adarsh.springdatajpaexp.model.PayStub>
) not compatible with managed type (io.adarsh.springdatajpaexp.model.PayStub).
which means that during the deserialization we can not annotate @JsonBackReference on the List or set because, during deserialization, its value is set to an instance that has the "managed" (forward) link.
So let's say first we have set the
@Entity
public class Employee {
@OneToMany
@JsonManagedReference
List<PayStub> pasytubs;
}
and,
@Entity
public class PayStub {
@ManyToOne
@JsonBackReference
Employee employee;
}
so during deserialization hibernate will get to know that here parent is Employee and the child is PayStub which is having the @JsonBackReference, so while deserializing it will try to set the value of the employee field which is in the PayStub entity with the one which has the "managed" (forward) link (Employee entity) and it will successfully perform it.
But when we will switch the annotation
@Entity
public class Employee {
@OneToMany
@JsonBackReference
List<PayStub> pasytubs;
}
and,
@Entity
public class PayStub {
@ManyToOne
@JsonManagedReference
Employee employee;
}
Now when it goes to the @JsonBackRefernece and tries to set the value with the one which has managed reference (so it can't set a List value with a normal bean value(Paystub)).
Upvotes: 2