@Entity
public class A {
@GeneratedValue
@Id
private long id;
public long getId() {
return id;
}
public void setId(final long id) {
As stated in Nikos Paraskevopoulos' answer below, JPA and java objects require you to set both sides of a relationship. As long as you set the owning side, the database will be updated with the relationship changes, but the non-owning side will only reflect what is in the database if you manually set it, or you force it to be refreshed or reloaded. Reading the entity from a separate context does not force reloading, as your JPA provider can use a second level cache; this is the default in EclipseLink. Your other read is returning the A from the shared cache, which like your original object, does not have B added to its list of Bs.
The easiest solution is to just set B into A's list upfront. Other options here though would be to force the refresh of A using em.refresh(a) or with a query hint, or disable the shared cached.