I am using the JPA in my webapp and I can\'t figure out how to persist two new entities that relate to each other. Here an example:
You can persist one object and its child at a time. So I think this should work:
ProfilePicture profilePicture = new ProfilePicture("http://www.url.to/picture.jpg"); // create the picture object
Consumer consumer = new Consumer("John Doe"); // create the consumer object
consumer.setProfilePicture(profilePicture);
consumerFacade.create(consumer);
When persisting an instance of the non-owning side of the relationship (that which contains the 'mappedBy' and in your case Consumer) then you must always ensure both sides of the relationship are set to have cascading work as expected.
You should of course always do this anyway to ensure your domain model is correct.
Consumer c = new Consumer();
ProfilePicure p = new ProfilePicture();
c.setProfilePicture(p);//see implementation
//persist c
Consumer.java
@Entity
@Table(name = "Consumer")
@NamedQueries({...})
public class Consumer implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 50)
@Column(name = "userName")
private String userName;
@OneToOne(cascade = CascadeType.ALL, mappedBy = "consumer")
private ProfilePicture profilePicture;
public void setProfilePicture(ProfilePicture profilePicture){
//SET BOTH SIDES OF THE RELATIONSHIP
this.profilePicture = profilePicture;
profilePicture.setConsumer(this);
}
}
Always encapsulate add/remove to relationships and then you can ensure correctness:
public class Parent{
private Set<Child> children;
public Set<Child> getChildren(){
return Collections.unmodifiableSet(children); //no direct access:force clients to use add/remove methods
}
public void addChild(Child child){
child.setParent(this);
children.add(child);
}
public class Child(){
private Parent parent;
}