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...)
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... :)
I guess an horrible way of doing it would be deleting all.
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.
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.
Preventing SQL Injection you can use:
String escapedSQL = StringEscapeUtils.escapeSql(unescapedSQL);
from Apache Commons-Lang
method StringEscapeUtils.escapeSql