Hibernate还是SQL进行删除操作?

发布于 2025-01-08 15:29:00 字数 652 浏览 0 评论 0原文

我需要根据某个键删除表中的条目,这些条目可能达到 500 万左右。有两种方法可以解决这个问题。一种使用 Hibernate,另一种通过直接 SQL 查询。

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";

两者中哪一个会更快得到结果? Hibernate 查询可以进一步调整吗?

(如有语法错误请忽略)

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

动听の歌 2025-01-15 15:29:00

第二个肯定会更快,但有显着差异,因为在第一个中,您为每个删除执行一个查询,但在第二个中,您只发送一个查询,而您的 DBMS 处理其余的。

你可以通过Hibernate、HSQL执行第二个。

编辑:
顺便说一句,如果您对每个 ID 运行“DELETE FROM”查询,它几乎会像第一个查询一样慢,除非您不会迭代整个 Employee 记录,这更好:)
使用 SQL 的 IN() 运算符

"delete from Employee where Id IN(3,5,8,...);"
"delete from Employee where Id IN(SELECT Id FROM table...);"

尝​​试最小化 SQL 查询执行次数,如果您仍然对性能不满意,请尝试通过改进查询本身而不是编程部分来提高性能。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文