Hello!
I have a problem with a native SQL "Query" which is actually no query (i.e. a SELECT statement), but rather a DELETE statement.
I have to delete a lot of entries of a database. My first try was something like
Code:
Query q = session.createQuery("from Cat cat where cat.id<1000");
for (Iterator i = q.iterate(); i.hasNext(); ) {
session.delete(i.next());
}
With this approach, all the cat objects that are to be deleted will be loaded first, which results in bad performance (there seem to be different opinions whether this is good or not). So I tried to use another approach with native SQL queries:
Code:
Query q = session.createQuery("from Cat cat where cat.id<1000");
for (Iterator i = q.iterate(); i.hasNext(); ) {
Query delQuery = session.createSQLQuery("delete from cat {cat} where cat.id=:id", "cat", Cat.class);
delQuery.setLong("id", ((Cat)i.next()).getId());
delQuery.list(); // Ooops!
}
Now, this code crashes, because finally I end up with a JDBC Statement.executeQuery("delete ..."), which is of course wrong: It should be Statement.execute() instead.
Is there another possibility except Session.list() and Session.iterate() to execute a query, which results in a Statement.execute() instead of a Statement.executeQuery()?
Or can this be done in another, efficient way?
Thanks!
Christian