Search code examples
hibernatejpa-2.0entitymanager

Does EntityManager refresh() cause to cascade synchronization through entities multi-level relation?


I have three entities 'A', 'B', 'C':


@Entity
public class A implements Serializable {
    ... 

    private B b;  

    @OneToOne(mappedBy = "a", fetch = FetchType.LAZY)
    @Cascade({CascadeType.ALL})
    public B getB() {
        return b;
    }

    public void setB(B b) {
        this.b = b;
    } 

    ...
}

@Entity
public class B implements Serializable {
    ...

    private A a;

    @OneToOne(fetch = FetchType.LAZY)
    public A getA() {
         return a;
    }

    public void setA(A a) {
         this.a = a;
    }

    ...

    private Collection<C> cCollection;

    @OneToMany(mappedBy = "b", fetch = FetchType.LAZY)
    public Collection<C> getCCollection() {
        return cCollection;
    }

    public void setCCollection(Collection<C> cCollection) {
        this.cCollection = cCollection;
    }
    ...
}

@Entity
public class C implements Serializable {
    ...

    private B b;
    @ManyToOne(optional = false, fetch = FetchType.LAZY )
    public B getB() {
        return b;
    }

    public void setB(B b) {
        this.b= b;
    }
}

When I update B.cCollection -add or remove C objects- and then refresh object a, I'll expect these changes affect results of a.getB().getCCollection(), but it never happens and cCollection list won't be updated. Am I wrong with refresh() operation?

//Adding or removal C objects to/from a.getB().getCCollection()
//Persisting changes
myEM.refresh(a);

(Note: I use hibernate and JPA 2.0. Persisting data in database has no problem and works truly).


Solution

  • you should use merge method instead: http://docs.oracle.com/javaee/5/api/javax/persistence/EntityManager.html

    myEM.merge(a);