Spring Repositories returning Lists example

The Spring Data CrudRepository has various methods that return multiple instances of the entity managed by the repository. It does so by using Iterable and not List, as one might expect. In many cases, that is of no consequence, since you typically want to iterate over the result anyway. However, you might occasionally prefer a List. In these cases, Iterable is annoying.

I will write more about why that choice was made in the first place and how you can deal with it as long as you are on Spring Data 2.x. However, let me get the good news out first:

Repositories returning Lists

Spring Data 3.0.0-M2 now offers a ListCrudRepository, which returns a List where CrudRepository returns an Iterable.

Example 1. CrudRepository versus ListCrudRepository
@NoRepositoryBean
public interface CrudRepository<T, ID> extends Repository<T, ID> {

<S extends T> S save(S entity);

<S extends T> Iterable<S> saveAll(Iterable<S> entities);

Optional<T> findById(ID id);

boolean existsById(ID id);

Iterable<T> findAll();

Iterable<T> findAllById(Iterable<ID> ids);

long count();

void deleteById(ID id);

void delete(T entity);

void deleteAllById(Iterable<? extends ID> ids);

void deleteAll(Iterable<? extends T> entities);

void deleteAll();
}
@NoRepositoryBean
public interface ListCrudRepository<T, ID> extends CrudRepository<T, ID> {

<S extends T> List<S> saveAll(Iterable<S> entities);

List<T> findAll();

List<T> findAllById(Iterable<ID> ids);
}

Splitting the Sorting Repositories

The popular PagingAndSortingRepository used to extend from CrudRepository, but it no longer does. This lets you combine it with either CrudRepository or ListCrudRepository or a base interface of your own creation. This means you now have to explicitly extend from a CRUD fragment, even when you already extend from PagingAndSortingRepository.

Example 2. Paging and sorting repository — Version 2.x
public interface PersonRepository<Person, Long> extends PagingAndSortingRepository<Person, Long> {}COPY
Example 3. Paging and sorting repository — Version 3.x
public interface PersonRepository<Person, Long> extends PagingAndSortingRepository<Person, Long>, ListCrudRepository<Person, Long> {}COPY
There are also other interfaces that return Iterable<T> and that now got a companion interface that returns List<T>.

New fragment interface returning List

ListQuerydslPredicateExecutor
ListQueryByExampleExecutor

Sorting fragment Interface

ReactiveSortingRepository
Rx3JavaSortingRepository
CoroutineSortingRepository

CRUD repository it no longer extends

ReactiveCrudRepository
CoroutineCrudRepository
Rx3JavaCrudRepository

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation