动机
这对我不起作用,我设置了
<property name="show_sql">true</property>
并且输出没有说明任何类似的内容...ON DELETE CASCADE...
。
我找到了另一个对我有用的解决方案:
假设您有一个作者类和一个作者书籍类,并且您希望在删除作者时自动删除所有书籍(通过休眠,sql-query,...),并且您不能(总是)删除的原因是会话.删除()。
也许:
session.createSQLQuery("DELETE FROM author").executeUpdate();
解决方案
所以你的作者类可能看起来像这样:
@Entity
@Table(name = "author")
public class Author {
@Id
@GeneratedValue(generator = "increment")
@GenericGenerator(name = "increment", strategy = "increment")
@Column(name = "ID")
private Integer id;
@Column(name = "NAME")
private String name;
@OneToMany(mappedBy = "author")
private Set<Book> books;
...
课本看起来像这样:
@Entity
@Table(name = "book")
public class Book {
@Id
@GeneratedValue(generator = "increment")
@GenericGenerator(name = "increment", strategy = "increment")
@Column(name = "ID")
private Integer id;
@Column(name = "TITLE")
private String title;
@ManyToOne
@JoinColumn(name = "AUTHOR_ID", foreignKey = @ForeignKey(name = "FK_BOOK_author_AUTHOR_ID"))
private Author author;
...
诀窍是使用自己命名外键约束
foreignKey = @ForeignKey(name = "FK_BOOK_author_AUTHOR_ID")
然后添加
<property name="hibernate.hbm2ddl.import_files">update.sql</property>
到您的hibernate.cfg.xml(不要忘记hibernate.hbm2ddl.auto)。update.sql然后包含表约束的更新:
ALTER TABLE `book` DROP FOREIGN KEY `FK_BOOK_author_AUTHOR_ID`;
ALTER TABLE `book` ADD CONSTRAINT `FK_BOOK_author_AUTHOR_ID` FOREIGN KEY (`AUTHOR_ID`) REFERENCES `author`(`ID`) ON DELETE CASCADE;
因此,hibernate 总是能够删除/更改约束,因为它知道约束的名称——您还应该检查@Cascade 设置——并且您必须实施一个策略来处理会话中对象的删除!