使用 hibernate/hql 截断表?
使用 hibernate/hql 截断表的推荐方法是什么?
我已经尝试过这个:
Query query = session.createQuery("truncate table MyTable"); query.executeUpdate();
但它不起作用(截断似乎没有在 hql 中的任何地方记录......)
What is the recommended way to truncate a table using hibernate/hql?
I've tried this:
Query query = session.createQuery("truncate table MyTable"); query.executeUpdate();
But it didn't work (truncate doesn't seem do be documented anywhere in hql...)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
注意,truncate 和delete 是完全独立的sql 语句:
如果将它们全部放在一起:
,因此请注意您真正想要使用的语句。
至于如何使用 hql 截断表,应该禁止从应用程序运行 DDL(截断、创建表、删除表等)。 你应该使用删除。 但如果桌子很大,它也不起作用。
这就是为什么清空应用程序中的表通常是一个坏主意。
如果您想做一些清理,通常最好每晚在 sql 脚本中运行一次 truncate。
请注意,我不知道您的应用程序的具体情况,它只是笼统地说。
Be careful, truncate and delete are totally separate sql statements :
If you put it all together :
so be careful of what statement you really want to use.
As to how truncating a table with hql, it should be forbidden to run DDL (truncate, create table, drop table, etc...) from and application. You should use delete. But if the table is large, it won't work, either.
That's why emptying a table in an application is in general a bad idea.
If you want to do some cleaning, it is often better to run truncate inside an sql script once each night.
Notice that I don't know the specifics of your application and that it is only talking in general.
我想一个可怕的方法就是删除所有内容。
I guess an horrible way of doing it would be deleting all.
我在 HQL 中使用了删除语法来保持可移植性。 效果很好:
效果很好并且完全截断了目标表。 请谨慎使用,因为您的数据库服务器将以极高的效率执行此语句...:)
I used the delete syntax in an HQL to maintain portability. Works great:
Works great and totally truncates the targeted table. Use with caution as your db server will perform this statement with great efficiency... :)
防止 SQL 注入,您可以使用:
String escapedSQL = StringEscapeUtils.escapeSql(unescapedSQL);
来自 Apache Commons-Lang
方法 StringEscapeUtils.escapeSql
Preventing SQL Injection you can use:
String escapedSQL = StringEscapeUtils.escapeSql(unescapedSQL);
from Apache Commons-Lang
method StringEscapeUtils.escapeSql
你可以这样做:
You can do it in this way:
您可以使用
session.createSQLQuery()
来代替:不用说,这在可移植性方面并不理想。 在映射中定义此查询并在代码中将其检索为命名查询可能是个好主意。
You can use
session.createSQLQuery()
instead:Needless to say, this is not ideal in terms of portability. It's probably a good idea to define this query in mapping and retrieve it in code as named query.