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.
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? How can I solve this?
Any suggestions are appreciated!
Thanks a lot, Davide.
You're on the right track - try amending your cascade to
This should work because you have a Join table.