21

I have a simple question: why JpaRepository is returning List of entities but CrudRepository returns Iterable of entities?

Is it done on purpose? I guess it's because CrudRepository is more generic interface and there may be some specific repository which returns Iterable.

It makes harder to use CrudRepository without using specific JpaRepository..

Thanks

Vadim Kirilchuk
  • 3,532
  • 4
  • 32
  • 49
  • I don't see why it is harder can you give an example ? – Rafik BELDI Aug 07 '15 at 16:15
  • Say, I want to get size of the returned items, in case of CrudRepository I'll have to count manually while(hasnext) counter++, on the list I can simply call size(). There are other similar things. – Vadim Kirilchuk Aug 07 '15 at 16:46

2 Answers2

27

The class CrudRepository is part of the Spring Data Commons project and is the recommended interface to extend regardless of the actual data store used.

The reason CrudRepository methods return Iterable and not List (or Set) is because some data stores allow streaming of results and using a Collection type would result in loss of functionality for such stores.

manish
  • 19,695
  • 5
  • 67
  • 91
  • Yes, that seems like an answer I was expecting. Can you give any example of such store please? After that I will accept the answer. Thanks – Vadim Kirilchuk Aug 09 '15 at 11:04
  • 1
    Check the last link in my answer where the Spring Data team has clarified the issue and given examples of data stores that provide streaming support. – manish Aug 09 '15 at 14:59
  • 7
    To address concerns you have mentioned in your question, you can always have `interface BaseRepository extends CrudRepository { @Override List findAll(); }`. This is also what `JpaRepository` does. This way, you can stick to the generic `CrudRepository` and still get the same functionality you are looking for (`Collection.size()`, etc.). – manish Aug 09 '15 at 15:02
  • The last comment is awesome, will try to do that, thanks! – Vadim Kirilchuk Aug 09 '15 at 18:38
4

JpaRepository extends PagingAndSortingRepository

and PagingAndSortingRepository extends CrudRepository.

This allows JpaRepository to have a more specific return type of Itrable which is List

Rafik BELDI
  • 4,140
  • 4
  • 24
  • 38