JPA entity with ManyToOne relationship JSON Serialization JPA entity with ManyToOne relationship JSON Serialization json json

JPA entity with ManyToOne relationship JSON Serialization


Why don't you create a object dedicated to JSON communication instead of using the Entity ?

you can't do this :

{       "BName": "foo",      "AName": "bar",                  ...    }

because it will try to unserialize a String into a A object

create a DTO class

class BDTO {    private String AName;    private String Bname}

bind it in your controller BDTO instead of B

@RequestBody BDTO bDTO

then you can do

B b = new B();b.setBName(bDTO.getBName());b.setAName(yoursession.find(bDTO.getAName()));yoursession.saveOrUpdate(b);

Another solution : if you want to keep Entity as transfert object is to set only the ID in your request :

{   "BName": "foo",  "AName": {"AName": "bar" }   ...}

You don't have to set all the sub properties of AName only the @ID is enough, in your controller you can simply do a find() for the A object and set it on B then saveOrUpdate your B object :

b.setAName(yoursession.find(b.getAName().getAName()));


Since Jackson 1.9 you can define your nested class field with @JsonUnwrapped annotation to indicate to Jackson that a contained object should be unwrapped during serialization i.e. the contained object properties should be included among the properties of the parent.

public class B implements Serializable {

...

@ManyToOne@JoinColumn(name="AName")@JsonUnwrappedprivate AName;