[英]Hibernate ManyToMany Delete
I have some trouble on deleting a content when is present a many to many relation with another object. 与另一个对象存在多对多关系时,删除内容时遇到一些麻烦。
To perform delete I have an array of named query and to delete, I loop through the array and perform delete, entity per entity, like this: 为了执行删除,我有一个名为查询的数组并要删除,我遍历该数组并针对每个实体执行删除,如下所示:
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);
}
}
When iteration try to perform EntityWithManyToMany.deleteByContentId HQL batch query, I can see on the logs the translated sql instruction, but followed by a set of insert of the same row and MySQL rightly returns me a constraint error. 当迭代尝试执行EntityWithManyToMany.deleteByContentId HQL批处理查询时,我可以在日志上看到已翻译的sql指令,但是后面跟随着同一行的插入,而MySQL正确地向我返回了约束错误。
This is my many to many relation object I try to delete: 这是我尝试删除的多对多关系对象:
@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;
}
Do you think it's possible the problem concern CascadeType? 您是否认为问题可能与CascadeType有关? How can I solve this?
我该如何解决?
Any suggestions are appreciated! 任何建议表示赞赏!
Thanks a lot, Davide. 非常感谢Davide。
You're on the right track - try amending your cascade to 您步入正轨-尝试将级联修改为
cascade = {CascadeType.PERSIST, CascadeType.DELETE}
This should work because you have a Join table. 这应该起作用,因为您有一个Join表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.