Suppose we have standard one-to-many relationship between Parent and Child objects. In other words, one Parent holds list of Child objects.
Mapping is standard... Ids in both classes are annotated with @GeneratedValue(strategy = GenerationType.IDENTITY)... There are all getters and setters...
Parent{
....
@OneToMany(cascade = CascadeType.ALL, mappedBy = "parent")
Collection<Child> children;
....
}
Child{
...
@ManyToOne(optional = false)
Parent parent;
...
}
Child object is the owning side of relation. When I save owning Child object, and after that fetch Parent object, I expect to get previously saved Child within parent. More precise, when I execute this code:
EntityManager em...
Parent p = new Parent();
em.persist(p);
em.flush();
Child c = new Child();
c.setParent(p);
em.persist(c);
em.flush();
Parent savedParent = em.find(Parent.class, p.getId());
savedParent.getChildren().size(); //this call returns 0 instead of 1 (why?)
...I expect that savedParent has in collection previously saved one child. But, for some reason, this does not work. Any ideas?