What is the best way to delete all rows in a table in Hibernate?
If I iterate over a collection and call session.delete()
it\'s not perform
DELETE FROM enityName
The problem lies in the fact that hibernate handles cascades internally, rather than leaving this to the database. So sending a query won't trigger the internal cascades, hence you will have inconsistencies / orphans.
If performance is so crucial (after all it's not everyday that one truncates a table), then you can have more than 1 HQL delete for each cascade - i.e. handling the cascades manually.
You can use HQL for truncate table
public int hqlTruncate(String myTable){
String hql = String.format("delete from %s",myTable);
Query query = session.createQuery(hql)
return query.executeUpdate();
}
String stringQuery = "DELETE FROM tablename";
Query query = session.createQuery(stringQuery);
query.executeUpdate();