Using hibernate/hql to truncate a table?

后端 未结 6 1391
借酒劲吻你
借酒劲吻你 2020-12-29 06:45

What is the recommended way to truncate a table using hibernate/hql?

I\'ve tried this:

 Query query = session.createQuery(\"truncate table MyTable\");
 qu         


        
6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-29 06:49

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

提交回复
热议问题