我遇到了一个问题,我试图在Hibernate中进行删除操作。每次我尝试删除时,由于存在子记录,我得到一个问题,因此无法删除父项。我想删除孩子和父母。这里是我的父映射:休眠级联删除不起作用
<set name="communicationCountries" inverse="true" cascade="all,delete-orphan">
<key column="COM_ID" not-null="true" on-delete="cascade" />
<one-to-many class="com.fmr.fc.portlet.communications.vo.CommunicationCountry"/>
</set>
这里是子类的映射:
<many-to-one name="communication" column="COM_ID" not-null="true" class="com.fmr.fc.portlet.communications.vo.Communication" cascade="all"/>
编辑 - 当我插入的数据插入到家长和孩子。
当我使用一个新的对象的ID与对象的ID进行更新时,我想要修改父级更新,但是第二次添加任何现有的子级。我似乎无法删除孩子。当我使用ID检索一个对象并修改它时,我得到一个错误告诉我org.hibernate.LazyInitializationException:无法初始化代理 - 拥有的Session被关闭。我怀疑这是因为在一个getHibernateTemplate()调用中,我得到的对象,我将它保存在另一个,这是两个不同的会话?
当我做删除时,我得到一个错误,因为孩子存在。我知道我只是在做一些愚蠢的事情,因为缺乏对这一切如何运作的线索。
这里是我的更新和删除方法,在这种情况下,更新/保存是在保存前检索和修改。删除使用新的对象具有相同ID作为一个在DB我想删除:
public void deleteCommunication(Communication comm) throws DataAccessException
{
getHibernateTemplate().delete(comm);
}
public void saveCommunication(Communication comm) throws DataAccessException
{
Communication existing = (Communication)getHibernateTemplate().load(Communication.class, comm.getComId());
existing.getCommunicationCountries().clear();
getHibernateTemplate().saveOrUpdate(existing);
}
UPDATE 因此,这里有我的新方法,但仍然没有喜悦。我认为我的问题与未加载/初始化等的儿童有关。虽然删除,但我不明白为什么没有发生级联删除。
非常感谢您的帮助。我已经达到了我对这项工作已经截止,所以如果我不把它固定在周末我只是将不得不求助于执行HQL查询,因为我知道,会为我工作:(
public void deleteCommunication(Integer id) throws DataAccessException
{
HibernateTemplate hibernate = getHibernateTemplate();
Communication existing = (Communication)hibernate.get(Communication.class, id);
hibernate.initialize(existing.getCommunicationCountries());
hibernate.delete(existing);
}
public void updateCommunication(Communication comm) throws DataAccessException
{
HibernateTemplate hibernate = getHibernateTemplate();
Communication existing = (Communication)hibernate.get(Communication.class, comm.getComId());
hibernate.initialize(existing.getCommunicationCountries());
existing.getCommunicationCountries().clear();
hibernate.saveOrUpdate(existing);
}
你可以添加hibernate映射吗?你有没有为关系指定级联? – 2009-09-17 15:34:22
'all,delete-orphan'不是级联标识符。 'all-delete-orphan'是。 – Jherico 2009-09-17 17:54:40
@Jherico - 两者完全一样:http://docs.jboss.org/hibernate/stable/core/reference/en/html/collections.html#collections-mapping。 “all”和“delete-orphan”是有效的级联操作,可以用逗号分隔多个值。 – ChssPly76 2009-09-17 18:23:07