Reputation: 4698
Consider the below two methods to delete a Set of Employees with the name "John" .
List<Employee> list = new ArrayList<Employee>();
String query= " from Employee emp where emp.name = 'John'";
list=getHibernateTemplate().find(query);
First Method:
getHibernateTemplate().deleteAll(list);
Second Method:
Iterator<BulkChangeRequest> itList = list.iterator();
while(itList.hasNext()) {
Employee emp = itList.next();
getHibernateTemplate().delete(emp);
}
Do they differ significantly in terms of performance? Are both of them essentially the same i.e. does the deleteAll method delete row one by one?
Also wouldn't it be better to do it in SQL using the following query?
" delete from Employee where name = 'John'"
Upvotes: 4
Views: 16796
Reputation: 11617
I suggest you read this section, one shot delete
:
Deleting collection elements one by one can sometimes be extremely inefficient. Hibernate knows not to do that in the case of an newly-empty collection (if you called list.clear(), for example). In this case, Hibernate will issue a single DELETE.
Upvotes: 1
Reputation: 3128
Yes. It would be better to use SQL or HQL to delete all employee records named 'John' rather then the first option. Simply because in first option, you have to load all employee record from db to delete. That's obviously an extra task.
I think, for delete()
and deleteAll()
, there will be no difference except in delete()
, it will create new session for every call; whereas in deleteAll()
, all objects will be deleted in one session. But the number of queries will be the same.
Upvotes: 1