Do I have to set both sides for a bidirectional relationship?

前端 未结 2 477
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-10 16:49
@Entity
public class A {
    @GeneratedValue
    @Id
    private long id;

    public long getId() {
        return id;
    }

    public void setId(final long id) {         


        
2条回答
  •  再見小時候
    2020-12-10 17:05

    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.

提交回复
热议问题