当与另一个对象存在多对多关系时,我在删除内容时遇到了一些麻烦。
要执行删除,我有一个命名查询数组并要删除,我遍历数组并执行删除,每个实体的实体,如下所示:
private static final String[] DELETE_CONTENT_QUERY_NAMES = {
"Entity1.deleteByContentId",
"Entity2.deleteByContentId",
"Entity3.deleteByContentId",
"Entity4.deleteByContentId",
"Entity5.deleteByContentId",
"EntityWithManyToMany.deleteByContentId",
"Entity7.deleteByContentId",
"Content.DeleteByContent"
};
@Override
@Transactional
public void deleteContent(Content content) throws Exception{
Map<String, Object> params = new HashMap<String, Object>();
params.put("contentId", content.getContentId());
for (String queryName : DELETE_CONTENT_QUERY_NAMES) {
dao.batchDeleteByNamedQuery(queryName, params);
}
}
当迭代尝试执行EntityWithManyToMany.deleteByContentId HQL 批量查询时,我可以在日志上看到翻译后的 sql 指令,但后面跟着一组同一行的插入,MySQL 正确地返回了一个约束错误。
这是我尝试删除的多对多关系对象:
@Entity
@Embeddable
public class CategoryContent implements java.io.Serializable {
/***
* Private Declarations
*/
@EmbeddedId
@AttributeOverrides({
@AttributeOverride(name = "contentId", column = @Column(
name = "CONTENT_ID",
nullable = false, precision = 10, scale = 0)),
@AttributeOverride(name = "categoryId", column = @Column(
name = "CATEGORY_ID",
nullable = false, precision = 10, scale = 0))
})
@NotNull
private CategoryContentId id;
@ManyToOne(fetch = FetchType.EAGER, cascade=CascadeType.PERSIST)
@JoinColumn(name = "CATEGORY_ID", insertable=false, updatable=false)
private Category category;
@ManyToOne(fetch = FetchType.EAGER, cascade=CascadeType.PERSIST)
@JoinColumn(name = "CONTENT_ID", insertable=false, updatable=false)
private Content content;
@Column(name = "PRIORITY", nullable = true)
private Integer priority;
}
您认为问题可能与 CascadeType 有关吗?我该如何解决这个问题?
任何建议表示赞赏!
非常感谢,戴维德。