Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize JPA Entity with foreign key reference OR how to set foreign key ID for mapped entity

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!

like image 952
preston.m.price Avatar asked Nov 10 '22 20:11

preston.m.price


1 Answers

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.

like image 185
Shannon Avatar answered Nov 14 '22 21:11

Shannon