当与另一个对象存在多对多的关系时,我在删除内容方面遇到了一些麻烦。
要执行删除我有一个命名查询数组并要删除,我遍历数组并执行delete,每个实体的实体,如下所示:
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有关吗?我该如何解决这个问题?
任何建议都表示赞赏!
非常感谢, 的Davide。
答案 0 :(得分:0)
你走在正确的轨道上 - 尝试修改你的级联
cascade = {CascadeType.PERSIST, CascadeType.DELETE}
这应该有效,因为你有一个Join表。