Using hibernate/hql to truncate a table?

user149100 picture user149100 · Aug 11, 2009 · Viewed 44.8k times · Source

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...)

Answer

ChssPly76 picture ChssPly76 · Aug 11, 2009

You can use session.createSQLQuery() instead:

session.createSQLQuery("truncate table MyTable").executeUpdate();

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.