Jpa OneToMany can't stand a child

I'm having trouble saving the OneToMany field. These are two simplified classes I use for testing.

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 save the user, the child of the phoneNumber is not saved automatically. In the OO method, I just need to do one for many.

I am using EclipseLink.

Many thanks to all for your hints.

+6
source share
1 answer

You need to establish communication 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); 
+2
source

Source: https://habr.com/ru/post/900190/


All Articles