gpt4 book ai didi

java - Hibernate延迟初始化帮助

转载 作者:搜寻专家 更新时间:2023-10-30 22:22:23 24 4
gpt4 key购买 nike

我在尝试使用 hibernate 删除时遇到问题。当我尝试删除时,我得到一个异常,说 child 存在并且存在 FK 违规。我也想删除 child ,但删除似乎没有级联。在尝试解决此问题大约一周后,我读到我应该使用 HibernateInterceptor 来保持 session 打开,以便可以加载子项。现在,当我尝试执行此操作时,出现以下错误:

Failed to load portlet com.blah.blah.CommunicationsPortlet: java.lang.ClassCastException: $Proxy27 incompatible with com.blah.blah.HibernateCommunicationsDAOImpl

这是我的映射文件的摘录:

<set name="communicationCountries" inverse="true" cascade="all,delete-orphan">
<key column="COM_ID" not-null="true" on-delete="cascade" />
<one-to-many class="com.blah.blah.CommunicationCountry"/>
</set>

这是应用上下文的摘录:

<bean id="hibernateCommunicationsDAOImplTarget"
class="com.blah.blah.dao.impl.HibernateCommunicationsDAOImpl">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>

<bean id="hibernateCommunicationsDAOImpl" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target"><ref bean="hibernateCommunicationsDAOImplTarget"/></property>
<property name="proxyInterfaces">
<value>com.blah.blah.dao.CommunicationsDAO</value>
</property>
<property name="interceptorNames">
<list>
<value>hibernateInterceptor</value>
</list>
</property>
</bean>

这是我的 DAO 中的方法:

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);
}

我真的不知道我做错了什么。我没有非常复杂的模式,只有一个导致 child (国家/地区)的表格。我可以做些什么来解决这个问题?

最佳答案

如果您只是想连同子项一起删除父项,则不需要加载子项集合。你甚至不需要 get() parent ,使用load()够了:

public void deleteCommunication(Integer id) throws DataAccessException {
HibernateTemplate hibernate = getHibernateTemplate();
Communication existing = (Communication) hibernate.load(Communication.class, id);
hibernate.delete(existing);
}

当然,这假设适当的映射/级联到位。您显示的设置映射摘录是可以的,但 <key ... on-delete="cascade"/> 除外。环境。由于以下几个原因,这相当棘手:

  1. 您的数据库必须支持它并且您的模式必须定义它。如果不是这种情况,您将收到错误消息。
  2. 如果 cascade 设置为“ALL”,您将不会通过此设置获得任何性能改进,因为 Hibernate 将仍然加载每个子实体以检查进一步的关联。您需要将级联设置为“保存更新”才能使其正常工作,这会对具有托管生命周期的父子关系产生副作用。

因此我建议删除 on-delete="cascade"暂时不要使用它,直到您完全理解所有含义。

您提到的 HibernateInterceptor 与所有这些无关(当然与您编码的 delete() 方法无关);它是 open-session-in-view 的一部分与 UI 层通信的方法。

以下是解决上述所有问题的方法:

  1. 暂时摆脱 HibernateInterceptor。
  2. 编写单元测试以在一个事务中创建父/子项,提交,在第二个事务中删除它们,提交。
  3. 如果 (2) 不起作用,则您的映射和/或架构有问题。将两者都张贴在这里,我会看一看。
  4. 如果 (2) 确实起作用而您上面的 delete() 方法不起作用,那么您的代码中调用 delete() 的地方有问题。也许您正在加载相同的 Communication实例并覆盖其 communicationCountries Collection 。

关于java - Hibernate延迟初始化帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1455500/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com