我在使用Hibernate处理特定场景时遇到了一些困难...
考虑到上面的片段(简化模型),实体A和D已经存在。他们将获得新的儿童B和E,而E也有新的C儿童。然后我打电话给"合并"实体管理器中的方法。
@Entity
public class A {
@OneToMany(mappedBy = "a", fetch = FetchType.Lazy, cascade = CascadeType.All)
private List<B> bList;
}
@Entity
public class B {
@ManyToOne(fetch=FetchType.LAZY)
@JoinCollumn(name="ID_A")
private A a;
@OneToMany(mappedBy = "b", fetch = FetchType.Lazy, cascade = CascadeType.All)
private List<E> eList;
}
@Entity
public class C {
@ManyToOne(fetch=FetchType.LAZY)
@JoinCollumn(name="ID_E")
private E e;
}
@Entity
public class D {
@OneToMany(mappedBy = "d", fetch = FetchType.Lazy, cascade = CascadeType.All)
private List<E> bList;
}
// The "Double Parented" Children
@Entity
public class E {
@ManyToOne(fetch=FetchType.LAZY)
@JoinCollumn(name="ID_B")
private B b;
@ManyToOne(fetch=FetchType.LAZY)
@JoinCollumn(name="ID_D")
private D d;
@OneToMany(mappedBy = "e", fetch = FetchType.Lazy, cascade = CascadeType.All)
private List<C> cList;
}
public class Example {
public void newChildren() {
A a = getExistingAfromDatabase(); // defined elsewhere
E e = new E(); // then fills some attributes...
B b = new B(); // then fills some attributes...
b.getEs().add(e);
e.setB(b);
a.getBs().add(b);
b.setA(a);
edit(a);
}
public void edit(A myEntity) {
EntityTransaction trans = null;
EntityManager eMngr = getEntityManager(); // this is defined in another place
try {
trans = eMngr.getTransaction();
trans.begin();
eMngr.merge(myEntity);
trans.commit();
} catch (Exception e) {
if (trans != null && trans.isActive())
trans.rollback();
throw new DAOException("Error! " + e.getMessage(), e);
}
}
}
无论我选择合并的第一个实体(A或D),我都得到了相同的异常:org.hibernate.TransientObjectException:object引用未保存的瞬态实例 - 在刷新之前保存瞬态实例:E.b - &gt;乙
Hibernate能否使用Cascade处理这个问题?如果是这样,我做错了什么?
非常感谢!
答案 0 :(得分:0)
确保你总是同时设置父和子,所以拿A和B你应该在基类中有这种实用方法(例如A):
public void addChild(B child) {
child.setA(this);
this.bList.add(child);
}
此实用程序可以防止您获得此类异常。