Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hibernate and delete all

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?

like image 348
feiroox Avatar asked Aug 16 '10 10:08

feiroox


People also ask

How delete all data from table in Hibernate?

Deletion Using a JPQL Statement Hibernate supports DML-style delete operations: Foo foo = new Foo("foo"); entityManager. persist(foo); flushAndClear(); entityManager. createQuery("delete from Foo where id = :id") .

How do you delete in Hibernate?

In Hibernate, an entity can be removed from a database by calling the Session#delete() or Session#remove() . Using these methods, we can remove a transient or persistent object from datastore.

How can I delete multiple rows in Hibernate?

In a non-transactional environment, multiple rows can be deleted in a batch in Hibernate something like the following. Session session=HibernateUtils. getSessionFactory(). getCurrentSession(); session.

What is Cascade delete in Hibernate?

When you now remove an Author entity, Hibernate cascades the operation to all associated Book entities. From there, it cascades it to all associated Authors and from there to their Books and so on. So, in this example, Hibernate will cascade the remove operation from Author 1 to Book 1 and 2.


1 Answers

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(); } 
like image 157
Damian Leszczyński - Vash Avatar answered Sep 23 '22 20:09

Damian Leszczyński - Vash