What is the recommended way to truncate a table using hibernate/hql?
I\'ve tried this:
Query query = session.createQuery(\"truncate table MyTable\");
qu
I used the delete syntax in an HQL to maintain portability. Works great:
public abstract class GenericDAOImpl implements GenericDAO {
private Class persistentClass;
// Balance of dao methods snipped... :)
/**
* Clears all records from the targetted file.
* @throws DAOException
*/
public int truncate() throws DAOException {
Session s = getSession();
int rowsAffected = 0;
try {
Class c = getPersistentClass();
String hql = "delete from " + c.getSimpleName();
Query q = s.createQuery( hql );
rowsAffected = q.executeUpdate();
} catch ( HibernateException e ) {
throw new DAOException( "Unable to truncate the targetted file.", e );
}
return rowsAffected;
}
/**
* Returns a Class object that matches target Entity.
*
* @return Class object from constructor
*/
public Class getPersistentClass() {
return persistentClass;
}
Works great and totally truncates the targeted table. Use with caution as your db server will perform this statement with great efficiency... :)