Using hibernate/hql to truncate a table?

后端 未结 6 1393
借酒劲吻你
借酒劲吻你 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:50

    You can do it in this way:

        try (Session session = sessionFactory.openSession()) {
            session.doWork(connection -> {
                try (PreparedStatement preparedStatement = connection.prepareStatement("TRUNCATE TABLE " + tableName)) {
                    preparedStatement.executeUpdate();
                    System.out.printf("Truncated table: %s%n", tableName);
                } catch (SQLException e) {
                    System.err.printf("Couldn't truncate table %s: %s: %s%n", tableName, e, e.getCause());
                }
            });
        }
    

提交回复
热议问题