Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jpa OneToMany not persist child

Tags:

jpa

jpa-2.0

I've trouble on persistence of OneToMany field. These are two simplified classes I'm using to make test.

public class User implements Serializable {
...
private String name;
...
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private List<PhoneNumber> phoneNumbers;
...
}

public class PhoneNumber implements Serializable {
...
private String phoneNumber;
...
@ManyToOne()
private User  user;
...
}

So I want to do this:

User u = new User();
PhoneNumber p = new PhoneNumber();
u.setName("Alan");
u.getPhoneNumbers.add(p);

But when I persist the user u the phoneNumber child is not automatically persisted. In OO way, I only need to do a one to many composition.

I use EclipseLink.

Many thanks to all for your hints.

like image 885
Brutos Avatar asked Oct 27 '11 10:10

Brutos


1 Answers

You need to establish the relationship in both directions. Add p.setUser(u) to your code:

User u = new User();
PhoneNumber p = new PhoneNumber();
u.setName("Alan");
u.getPhoneNumbers.add(p);
p.setUser(u);
like image 65
Matt Handy Avatar answered Nov 10 '22 10:11

Matt Handy