Advantages of Stream and Spring Data

淺唱寂寞╮ 提交于 2020-02-21 10:34:09

问题


Some people override the CrudRepository's method findAll to return an Stream (java 8), but I saw they finally transform the Stream to a List in order to send it through a rest controller. Why are they using a Stream ? What is the advantage to use a Stream here? If they want to filter the records I think would be better filter on DataBase.


回答1:


This is already supported in Spring Data JPA, look here; so there's not real advantage to override those to return Stream. If you really want a Stream and some potential advantages that would come with it - use what already Spring Data JPA provides.

And also a different aspect is that in JPA Spec 2.2 this could be the default return type of some queries. The JPA interfaces Query and TypedQuery will get a new method called getResultStream().

So Spring Data will use techniques specific to a particular provider, like Hibernate or EclipseLink to stream the result.

By default getResultStream is just a list.stream implementation, but Hibernate already overrides that with ScrollableResult. This is way more efficient if you need to process a very big result set.




回答2:


There might be various reasons why people want to use Streams.

  1. If you do any processing that you can't or don't want to do in the database, Streams might be nicer to work with.

  2. It's so hip and "functional". Almost everybody still seems to be experimenting what the right combination of features is. So it is perfectly possible and even likely that there is no benefit in using Streams. But then, it doesn't cost much either.



来源:https://stackoverflow.com/questions/44642556/advantages-of-stream-and-spring-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!