日期:2014-05-18  浏览次数:20746 次

如何使hibernate根据外键来删除数据?
我有一个Customer类和Order类,两者是一对多关系。当我删除一个Customer对象,并级联删除与Customer关联的Order对象时,控制台输出了如下sql语句:
Hibernate: delete from TABLE_ORDER where id=?
Hibernate: delete from TABLE_ORDER where id=?
Hibernate: delete from TABLE_ORDER where id=?
Hibernate: delete from TABLE_ORDER where id=?
Hibernate: delete from TABLE_ORDER where id=?
Hibernate: delete from TABLE_ORDER where id=?
Hibernate: delete from TABLE_ORDER where id=?
Hibernate: delete from TABLE_ORDER where id=?
Hibernate: delete from TABLE_ORDER where id=?
Hibernate: delete from TABLE_ORDER where id=?
Hibernate: delete from TABLE_ORDER where id=?
Hibernate: delete from TABLE_ORDER where id=?
Hibernate: delete from TABLE_ORDER where id=?


要怎样配置才能让hibernate能按照如下方式级联删除与Customer关联的Order对象呢:
delete from TABLE_ORDER where customerId=?

------解决方案--------------------
@OneToMany(cascade=CascadeType.ALL)
这样应该是按照你要求的那样吧。或者,你在删除之前调用一下
getXXXList().removeAll()这样的方法
------解决方案--------------------
不知道你是否使用了注解,如果用了注解,看看1楼说的试试,如果没有使用注解,而且你不想自己在程序中写代码的话,可以在他们的映射关系(比如one-to-many等)中加上配置,cascade="delete"