问题
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 Stream
s.
If you do any processing that you can't or don't want to do in the database,
Stream
s might be nicer to work with.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
Stream
s. But then, it doesn't cost much either.
来源:https://stackoverflow.com/questions/44642556/advantages-of-stream-and-spring-data