Gregor Sklorz
Gregor Sklorz

Reputation: 1705

JPA: Adding Child Entity to Parent Entity

I could need some help since Iam confused by the docs:

I have a Parent JPA Entity:

public class Provider implements Serializable {
...
    @OneToMany(fetch = FetchType.LAZY)
    private List<Contact> contacts;

And the child:

public class Contact implements Serializable {
    ...
    @ManyToOne(fetch = FetchType.LAZY)
    private Provider provider;

And I want JPA to create the relationship if I just add on Contact.

e.g:

Contact c = new Contact();
c.provider = providerX;
repo.save(c);

What happen now is:

I know I could set the contact as a property to provider. providerX.contacts.add(c); ... repo.save(providerX) But this is a bit unhandy and dont feels right.

How can I config the Entities to create this relationship just on saving the contact?

Thanks for any help. Gregor

Upvotes: 1

Views: 4668

Answers (1)

Amer Qarabsa
Amer Qarabsa

Reputation: 6574

First of all you need to add mappedBy in the non owning entity to establish the bidirectional relation, and initialize the list so you only need to add to it when you need

 @OneToMany(fetch = FetchType.LAZY, mappedBy="provider")
private List<Contact> contacts = new ArrayList<>();//im supposing java 8

Then since your relation is bidirectional its logical to have each side of the relation mapped to the other, hence you will need to have reference of each side in the other side

Contact c = new Contact();
c.setProvider(providerX);
providerX.getContacts().add(c);//please use getters and setters  
repo.save(c);

And at the end you need to cascade the provider inside the contacts so that when you persist the contacts, the provider gets persisted

 @ManyToOne(fetch = FetchType.LAZY,cascade=CascadeType.PERSIST)
private Provider provider;

Upvotes: 3

Related Questions