Reputation: 4738
I need to delete entries from a table based on a key, and these entries might come to around 5 million. There are two ways to go about it. One using Hibernate and the other by direct SQL query.
Hibernate:
List<Employee> empList =
getHibernateTemplate()
.findByNamedParam("from Employee emp where emp.Id=:empId","empId",employeeId);
Iterator<Employee> empIter = empList .iterator();
while(empIter.hasNext()) {
Employee empTran = empIter.next();
getHibernateTemplate().delete("Employee", empTran);
SQL:
delete from Employee where Id = employeeId";
Which among the two will get the results faster? And can the Hibernate query be tuned further?
(Please ignore syntax errors if any)
Upvotes: 1
Views: 3502
Reputation: 900
Second one definitely will be faster with a significant difference because in the first one you execute a query for every deletion but in the second you only send one query and your DBMS handles the rest.
You can execute the second one through Hibernate, HSQL.
Edit: Btw, if you run your "DELETE FROM" query for every ID it will be slow almost as the first one, except you won't be iterating whole Employee records, which is better :) Use SQL's IN() operator
"delete from Employee where Id IN(3,5,8,...);"
"delete from Employee where Id IN(SELECT Id FROM table...);"
Try to minimize your SQL Query executions and after if you are still not satisfied with the performance try to improve the performance by the improving the query itself, not the programming part.
Upvotes: 2