读书人

Hibernate: 设A摘引了B则删A后可能要

发布时间: 2012-10-25 10:58:57 作者: rapoo

Hibernate: 设A引用了B,则删A后可能要evict(A.getB())

Hibernate: 设A引用了B,如果要先取A删A再取B删B,则删A后可能要evict(A.getB()),才能顺利删除B

否则,就会报错:a different object with the same identifier value was already associated with the session



原理是这样的:

?????? 第一步将A从数据库中取出时,它引用的B也从数据库中取出,两者同时成为持久化对象。A删除后,B是处于Session中的持久化对象

????? 第二步中又显式地将B从数据库中取出,加上第一步中取出的B,Session里就有两个B了。这时侯如果删B,就会报上面所说的那种错误。

?????? 因此,应该在删除A后立即将它引用了的B从Session中清除掉。即:

?????? A?? =? Session.load(A);

?????? Session.delete(A);

?????? Session.evict(A.getB());

?????? Session.delete(B);

===============================================
注意:evict()并不会级联,除非设置了相应的cascade
也就是说,如果B引用了C, evict(B)时不会自动evict(C)

看官方文档:

This operation cascades to associated instances if the association is mapped with cascade="all" or cascade="all-delete-orphan".?

读书人网 >软件架构设计

热点推荐