0

I have a table in an Oracle database.

I want to know how to delete its rows, or how to delete purely the table using Hibernate, but not by changing the corresponding mapped class. I mean, I want to do it ouside the mapped class, in a main Java method for example.

To read data, I always use native SQL queries with Hibernate.

To write data, I use session.save

But how do I do to delete data from a table, or delete the table ?

I looked at the Hibernate documentation, but the solution always involves changing the mapped class code by adding annotations...

I want a solution like the one I use to read and write data :

session.createSQLQuery("...");

Or

session.save(...);

Is there a solution like that ?

hydertza
  • 163
  • 1
  • 1
  • 11

2 Answers2

0

I found the answer in another Stackoverflow question :

Query to delete all rows in a table hibernate

If the table from which I want to delete the rows is named MyTable then, the answer is :

in HQL :

session.createQuery("delete from MyTable").executeUpdate();

in native SQL :

session.createSQLQuery("delete from MyTable").executeUpdate();

I should have looked longer in stackoverflow before posting this question, sorry for that.

Community
  • 1
  • 1
hydertza
  • 163
  • 1
  • 1
  • 11
0

HQL delete from Xyz will help, as without where clause it will affect every row:

EntityManager em = // .. get EntityManager
em.getTransaction().begin();
em.createQuery("delete from MyTable").executeUpdate();
em.getTransaction().commit();
Alex Salauyou
  • 14,185
  • 5
  • 45
  • 67