在使用数据库时,为什么要使用Java 8 Stream API而不是直接的hibernate / sql查询 [英] Why would you prefer Java 8 Stream API instead of direct hibernate/sql queries when working with the DB

查看:329
本文介绍了在使用数据库时,为什么要使用Java 8 Stream API而不是直接的hibernate / sql查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我在很少的项目中看到很多代码使用流来过滤对象,例如:

Recently I see a lot of code in few projects using stream for filtering objects, like:

library.stream()
          .map(book -> book.getAuthor())
          .filter(author -> author.getAge() >= 50)
          .map(Author::getSurname)
          .map(String::toUpperCase)
          .distinct()
          .limit(15)
          .collect(toList()));

使用它而不是直接HQL / SQL查询返回已经过滤的数据库是否有任何优势结果。

Is there any advantages of using that instead of direct HQL/SQL query to the database returning already the filtered results.

第二个方法不是更快吗?

Isn't the second aproach much faster?

推荐答案

如果数据最初来自数据库,最好在数据库中进行过滤,而不是获取所有内容并在本地过滤。

If the data originally comes from a DB it is better to do the filtering in the DB rather than fetching everything and filtering locally.

首先,数据库管理系统擅长过滤,它是他们主要工作的一部分,因此他们为它进行了优化。也可以通过使用索引来加速过滤。

First, Database management systems are good at filtering, it is part of their main job and they are therefore optimized for it. The filtering can also be sped up by using indexes.

其次,获取和传输许多记录并将数据解组为对象,以便在执行操作时丢弃大量数据本地过滤浪费了带宽和计算资源。

Second, fetching and transmitting many records and to unmarshal the data into objects just to throw away a lot of them when doing local filtering is a waste of bandwidth and computing resources.

这篇关于在使用数据库时,为什么要使用Java 8 Stream API而不是直接的hibernate / sql查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆