Hibernate: Issue with OnDelete Annotation
Hello I have the following two entities
@Entity
public class DocumentCollection {
@Id
@GeneratedValue
private Long id;
@OneToMany(targetEntity=Document.class,mappedBy="documentCollection",cascade=javax.persistence.CascadeType.ALL)
@OnDelete(action = OnDeleteAction.CASCADE)
@Casc开发者_JAVA技巧ade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
private Set<Document> documents;
...
}
And:
@Entity
public class Document {
@Id
@GeneratedValue
private Long id;
@ManyToOne
private DocumentCollection documentCollection;
...
}
When a DocumentCollection gets deleted, all referenced documents should be deleted too. But I'm getting this error:
Cannot delete or update a parent row: a foreign key constraint fails (`tms_db`.`document`, CONSTRAINT `FK3737353BEB85533C` FOREIGN KEY (`documentCollection_id`) REFERENCES `documentcollection` (`id`))
I also tried putting the @OnDelete Annotation in the document class but didn't work. So what am I missing? For your information, I'am using Hibernate 3.6.0.Final.
UPDATE: I did a mysql schema dump and noticed that there is no ON DELETE CASCADE statement in the document table schema. Hibernate only generates the foreign key constraints, which leads to the mentioned error. Has anybody an idea why hibernate does NOT generate the "ON DELETE CASCADE" statement?
Hope, somebody can help me thx
@OnDelete
annotation affects the way Hibernate generates database schema. If your schema is not generated by Hibernate, or haven't been updated after adding this annotation, it wouldn't work correctly.
If you want to use manually created database schema with @OnDelete(action = OnDeleteAction.CASCADE)
, you should manually define foreign key constraint in your schema as on delete cascade
.
精彩评论