Search code examples
springjava-8spring-data

Advantages of Stream and Spring Data


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.


Solution

  • 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.