hibernate and delete all

旧街凉风 提交于 2019-12-03 04:44:32

问题


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 performing to my knowledge.

If I use another option session.createQuery("delete ...") it doesn't affect persistence context.

When I should use these methods if there is no better variant?


回答1:


  • if you don't have anything to cascade, use the HQL delete DELETE FROM enityName
  • if you have cascades, iterate the collection and delete each one individually.

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.




回答2:


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();
}



回答3:


String stringQuery = "DELETE FROM tablename";
Query query = session.createQuery(stringQuery);
query.executeUpdate();


来源:https://stackoverflow.com/questions/3492453/hibernate-and-delete-all

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!