Java 休眠并删除所有
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3492453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
hibernate and delete all
提问by feiroox
What is the best way to delete all rows in a table in Hibernate?
在 Hibernate 中删除表中所有行的最佳方法是什么?
If I iterate over a collection and call session.delete()
it's not performing to my knowledge.
如果我迭代一个集合并调用session.delete()
它,我不知道它的性能。
If I use another option session.createQuery("delete ...")
it doesn't affect persistence context.
如果我使用另一个选项,session.createQuery("delete ...")
它不会影响持久性上下文。
When I should use these methods if there is no better variant?
如果没有更好的变体,我什么时候应该使用这些方法?
采纳答案by Bozho
- if you don't have anything to cascade, use the HQL delete
DELETE FROM enityName
- if you have cascades, iterate the collection and delete each one individually.
- 如果您没有任何要级联的内容,请使用 HQL 删除
DELETE FROM enityName
- 如果您有级联,请迭代集合并单独删除每个集合。
The problem lies in the fact that hibernate handles cascades internally, rather than leaving this to the database. So sending a query won't trigger the internal cascades, hence you will have inconsistencies / orphans.
问题在于 hibernate 在内部处理级联,而不是将其留给数据库。因此发送查询不会触发内部级联,因此您将有不一致/孤立。
If performance is so crucial (after all it's not everyday that one truncates a table), then you can have more than 1 HQL delete for each cascade - i.e. handling the cascades manually.
如果性能如此重要(毕竟截断表并不是每天都有的),那么您可以为每个级联删除 1 个以上的 HQL - 即手动处理级联。
回答by thelost
String stringQuery = "DELETE FROM tablename";
Query query = session.createQuery(stringQuery);
query.executeUpdate();
回答by Damian Leszczyński - Vash
You can use HQL for truncate table
您可以使用 HQL 截断表
public int hqlTruncate(String myTable){
String hql = String.format("delete from %s",myTable);
Query query = session.createQuery(hql)
return query.executeUpdate();
}