Hibernate:OnDelete Annotation的问题

时间:2011-05-18 13:44:46

标签: java hibernate annotations

您好 我有以下两个实体

@Entity
public class DocumentCollection {
  @Id
  @GeneratedValue
  private Long id;
  @OneToMany(targetEntity=Document.class,mappedBy="documentCollection",cascade=javax.persistence.CascadeType.ALL)
@OnDelete(action = OnDeleteAction.CASCADE)
@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
  private Set<Document> documents;
 ...
}

并且:

@Entity
public class Document {
  @Id
  @GeneratedValue
  private Long id;

  @ManyToOne
  private DocumentCollection documentCollection;
  ...
}

删除DocumentCollection时,也应删除所有引用的文档。 但是我收到了这个错误:

Cannot delete or update a parent row: a foreign key constraint fails (`tms_db`.`document`, CONSTRAINT `FK3737353BEB85533C` FOREIGN KEY (`documentCollection_id`) REFERENCES `documentcollection` (`id`))

我也尝试将@OnDelete Annotation放在文档类中,但是没有用。 那我错过了什么?为了您的信息,我正在使用Hibernate 3.6.0.Final。

更新:我做了一个mysql架构转储,发现文档表架构中没有ON DELETE CASCADE语句。 Hibernate只生成外键约束,这会导致上述错误。有没有人知道为什么hibernate不生成&#34; ON DELETE CASCADE&#34;声明?

希望,有人可以帮助我 THX

1 个答案:

答案 0 :(得分:3)

@OnDelete注释会影响Hibernate生成数据库模式的方式。如果您的架构不是由Hibernate生成的,或者在添加此注释后尚未更新,则它将无法正常工作。

如果要使用手动创建的数据库模式@OnDelete(action = OnDeleteAction.CASCADE),则应手动将模式中的外键约束定义为on delete cascade