我有一个简单的父/子obj双向关系定义。我想执行级联删除,这样当删除父级时,所有子级都将被删除,同时从父级删除一次。这是我的pojo类声明:
@Entity
@Table(name = "Agent_Assignment", schema = "xxx", catalog = "AAA")
public class AgentAssignment {
private Set<AgentAssignmentAttr> attributes = new HashSet<AgentAssignmentAttr>();
@OneToMany( fetch=FetchType.EAGER, cascade=CascadeType.ALL, orphanRemoval=true )
@JoinColumn(name="Agent_Assignment_GUID")
public Set<AgentAssignmentAttr> getAttributes() {
return attributes;
}
public void setAttributes(Set<AgentAssignmentAttr> attributes) {
this.attributes = attributes;
}
}
@Entity
@Table(name = "Agent_Assignment_Attr", schema = "xxx", catalog = "AAA")
public class AgentAssignmentAttr {
private AgentAssignment asgnmnt = null;
@ManyToOne( fetch=FetchType.EAGER )
@JoinColumn(name="Agent_Assignment_GUID", insertable=false, updatable=false)
public AgentAssignment getAssignment() {
return asgnmnt;
}
public void setAssignment(AgentAssignment assignment) {
this.asgnmnt = assignment;
}
}
要删除的代码是:
AgentAssignment assgnmnt = (...some HQL query to returns the AgentAssignment obj)
getSession().delete(assgnmnt);
执行上述删除调用时,会抛出异常:
org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
基本上,当登录Hibernate日志的SQL执行时,它不会调用&#34;更新&#34;在Agent_Assignment_Attr表中它应该删除的行,而是调用&#34;更新&#34;在行上设置外键列&#34; Agent_Assignement_GUID&#34;为null,如下所示:
/* delete one-to-many com.cs.mytime.acr.model.AgentAssignment.attributes */ update
MyTime.dbo.Agent_Assignment_Attr
set
Agent_Assignment_GUID=null
where
Agent_Assignment_GUID=?
2014/08/22 16:31:10.430 [TRACE] <http-bio-8080-exec-5> (BasicBinder.bind:81) - binding parameter [1] as [VARCHAR] - [CA91A4F3-6F7E-4188-B299-8E9DF17F0385]
感谢任何人帮助,看看是否有我错过的东西和正确的解决方案。感谢。
答案 0 :(得分:0)
您的映射是错误的。双向关联只能定义关联的映射方式一次。您所拥有的是两个不同的,无关的关联碰巧使用同一列。映射应该是
@OneToMany(mappedBy="assignment", fetch=FetchType.EAGER, cascade=CascadeType.ALL, orphanRemoval=true )
public Set<AgentAssignmentAttr> getAttributes() {
return attributes;
}
其中mappedBy
说:“我是在AgentAssignmentAttr.assignment
上定义和映射的双向关联的反面,
@ManyToOne( fetch=FetchType.EAGER )
@JoinColumn(name="Agent_Assignment_GUID")
public AgentAssignment getAssignment() {
return asgnmnt;
}
答案 1 :(得分:0)
为了获得删除而不是更新,我不得不使用这种方法:
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
@JoinColumn(name = "PARENT_ID", referencedColumnName = "PARENT_ID", updatable = false)
private List<ChildEntity> children;