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.
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);
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