【发布时间】:2013-08-06 21:43:16
【问题描述】:
@OneToMany(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER, orphanRemoval = true)
@JoinColumn(name = "FacilityId", referencedColumnName = "Id")
@ForeignKey(name = "FK_Schedule_Facility")
@Cascade(value = {org.hibernate.annotations.CascadeType.ALL})
@OrderBy("fromDay asc")
private Set<Schedule> schedules = new HashSet<Schedule>();
我在实体Location 中有这个设置。
在我的应用程序中,我使用 AJAX 构建了一个新集合。这并没有给我带来任何问题。我可以更改时间表中的值,甚至添加更多值。但我不能删除一个。它保留在数据库和集合中。
我在我的 DAO 中使用这种方法: 私有 SessionFactory sessionFactory;
public Facility saveOrUpdate(Facility facility){
sessionFactory.getCurrentSession().saveOrUpdate(facility);
return facility;
}
所以我在日志中得到了这个:
2013-08-06 17:44:43,444 [1219450701@qtp-169872652-2] DEBUG com.firstbankpr.os.common.data.dao.hibernate.FacilityHibernateDAO - Obtaining Session
2013-08-06 17:44:43,450 [1219450701@qtp-169872652-2] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 515, SQLState: 23000
2013-08-06 17:44:43,450 [1219450701@qtp-169872652-2] ERROR org.hibernate.util.JDBCExceptionReporter - Cannot insert the value NULL into column 'FacilityId', table 'OLS.dbo.Schedule'; column does not allow nulls. UPDATE fails.
在joinColumn注解中输入nullable = false后,错误消失。但它仍然没有正确删除我要删除的计划。
那么我做错了什么?我做了很多谷歌搜索。 Found bugs in Hibernate 3.5 不适用于我,因为我使用的是 3.6.7。 Found that hashcode and equals have to be implemented correctly and found that JPA and Hibernate annotations often clash with each other。我还发现双向关系在级联方面存在问题,但同样不适用于我。但除了所有这些搜索之外,我还没有找到解决方案。或者也许我忽略了一些东西。
请帮帮我,谢谢!
【问题讨论】:
-
它没有,正如标题中所说的那样是单向的
-
似乎有一些建议您需要致电
merge()而不是saveOrUpdate()。这对我来说没有意义,但值得一试。此外,您可以尝试删除@Cascade注释,当您在@OneToMany中使用级联元素时,这样做是没有意义的。最后,您确定要在事务提交后检查删除吗? -
试试这个:删除
@OneToMany注解中的“cascade”属性,保留@Cascade一个。此外,OrphanRemoval 是关于在删除父级时删除子级,这不是您想要做的。 -
我尝试只使用一个级联注释,但没有任何效果。我会尝试我猜的合并。
-
合并确实有效,谢谢!它甚至适用于集合定义上的两个注释。