I am trying to use Jackson to (de)serialize my JPA entities to/from JSON for purposes of publishing the entity state over our API. FWIW I'm using hibernate as the JPA provider.
The problem I'm running into can be illustrated with a simple One-To-Many example of Person to Address like this:
@Entity
@Table(name="Person")
public class Person implements Serializable
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
// getters & setters
}
@Entity
@Table(name="Address")
public class Address implements Serializable
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String addressStr;
@ManyToOne
@JoinColumn(name="personId")
private Person person;
// getters & setters
}
Now, I would like to be able to accept JSON such as this for a create address request:
{
"personId": 1,
"addressStr": "123 Somestreet. Fooville, AK. 11111"
}
and use the ObjectMapper to create my Address instance and persist it. However, I don't know of any way in which you can have both a mapped relationship to an entity AND a setter for it's foreign key.
Any ideas or guidance are greatly appreciated!
You could try to expose the foreign key as a property, as discussed in Hibernate - Foreign keys instead of Entities Just be careful because the value of the foreign key and the value of the object gettter won't always match up.
However, I think it's better to have some code that does the work of interpreting the JSON. Your code can get the personId
value, look up the entity from the database, produce a meaningful exception if it's not present, and set the person
property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With