I'm having trouble figuring out why exactly the owning side of a relationship isn't getting persisted on the other side when I POST a JSON object to my REST API (using Spring and Hibernate).
Mapped superclass with id field:
@MappedSuperClass
public class BaseEntity implements Serializable {
private static final long serialVersionUID = 11538918560302121L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
....
}
Owning class (extends NamedEntity which in turn extends BaseEntity):
@Entity
@DynamicUpdate
@SelectBeforeUpdate
@NamedQuery(name = "Chain.byId", query = "from Chain where id=:id")
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id", scope=Chain.class)
public class Chain extends NamedEntity {
private static final long serialVersionUID = 4727994683438452454L;
@OneToMany(mappedBy = "chain", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Campaign> campaigns = new ArrayList<Campaign>();
....
}
Owned class:
@Entity
@DynamicUpdate
@SelectBeforeUpdate
@NamedQuery(name = "Campaign.byId", query = "from Campaign where id=:id")
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id", scope=Campaign.class)
public class Campaign extends NamedEntity {
@ManyToOne
@JoinColumn(name = "chain_id")
private Chain chain;
....
}
The relevant part of my RestController:
@RequestMapping(value = "new", method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
@ResponseBody
public Chain saveChain(@RequestBody Chain chain) {
chainDAO.saveChain(chain);
return chain;
}
JSON request body:
{
"name": "mcdonald's",
"campaigns": [
{
"name": "summer1"
}
]
}
Relevant part of JSON response body:
{
"id": 1,
"name": "mcdonald's",
"campaigns": [
{
"id": 1,
"name": "summer1",
"rewards": [],
"startDate": null,
"endDate": null,
"chain": null,
"surveys": [],
"achievements": []
}
],
"rewards": []
}
I suspect that this is actually the expected behaviour when using the @JsonIdentityInfo annotation to break infinite recursion? However, when I then try to request the Chain that I just created with its id field, I don't see the nested object (Campaign) anymore.
GET method I used to retrieve the Chain object I just created:
@RequestMapping(value = "{id}", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public Chain getChain(Model model, @PathVariable int id) {
Chain chain = chainDAO.getChainById(id).get(0);
return chain;
}
JSON response body for GET method:
{
"id": 1,
"name": "mcdonald's",
"campaigns": [],
"rewards": [],
"managers": [],
"locations": []
}
As you can see, the campaigns array in this Chain object is now empty.