
# Repositories

A repository is an `abstract interface class` that extends one of the starter's repository interfaces. The generator writes its implementation and registers it as a bean, with no annotation needed. You inject it by its type, like any bean.

## Why

The code behind `findById`, `save` and `deleteById` is the same for every aggregate. Spring Data writes it once; you only declare what is special to your aggregate: its finders. Because the build writes the class, a wrong method name is a build error, and there is nothing to discover by reflection at run time.

## Example

```dart
abstract interface class BookRepository
    implements
        ListCrudRepository<Book, int>,
        ListPagingAndSortingRepository<Book, int> {
  Future<List<Book>> findByTitle(String title);
}

@Service()
class Shelf {
  Shelf(this.books);

  final BookRepository books;

  Future<Book> rename(int id, String title) async {
    final book = await books.findById(id) ??
        (throw StateError('No book $id'));
    book.title = title;
    return books.save(book); // an update: the id is set and the version is not 0
  }
}
```

## The interfaces

| Interface | What it offers |
|---|---|
| `DataRepository<T, ID>` | Nothing: only the methods you declare (derived queries, `@Query`). Spring's `Repository`. |
| `CrudRepository<T, ID>` | `save`, `saveAll`, `findById`, `existsById`, `findAll`, `findAllById`, `count`, `deleteById`, `delete`, `deleteAllById`, `deleteAllOf`, `deleteAll`; collections as `Iterable`. |
| `ListCrudRepository<T, ID>` | The same, with `List` results. |
| `PagingAndSortingRepository<T, ID>` | `findAllSorted(Sort)` and `findAllPaged(Pageable)`. |
| `ListPagingAndSortingRepository<T, ID>` | The same, `findAllSorted` returning a `List`. |

`T` is the `@Table` class, `ID` the type of its `@Id`. A generic interface (`BaseRepository<T>`) is a base for others and never a bean, as with Spring's `@NoRepositoryBean`.

## The CRUD methods

| Method | What it does |
|---|---|
| `Future<T> save(T entity)` | Inserts a new entity, updates an existing one, and returns it saved, with the id the store gave and the version raised. With `@Version`, an update matches on the loaded version and throws `OptimisticLockingFailureException` when another save got in between. |
| `saveAll(Iterable<T>)` | Saves each one in turn and returns them saved. |
| `Future<T?> findById(ID id)` | The aggregate with its children, or `null`. |
| `Future<bool> existsById(ID id)` | Whether it exists. |
| `findAll()` | Every aggregate. |
| `findAllById(Iterable<ID>)` | The aggregates whose ids are listed; missing ids are skipped. |
| `Future<int> count()` | The number of aggregates. |
| `deleteById(ID id)` | Deletes it with its children; nothing when there is none. The version is not checked. |
| `delete(T entity)` | Deletes it with its children; checks the `@Version` as `save` does. |
| `deleteAllById(Iterable<ID>)` | Deletes the listed ids. |
| `deleteAllOf(Iterable<T>)` | Deletes each entity as `delete` does. Spring's `deleteAll(Iterable)`: Dart has no overloading. |
| `deleteAll()` | Deletes every aggregate. |

How `save` decides between insert and update is on [Entities](entities.md). An update of an entity whose row is gone, without a `@Version`, throws `IncorrectUpdateSemanticsDataAccessException`.

## Only the methods you want

Extend `DataRepository` when the whole CRUD set is too much, for example a read-only view:

```dart
abstract interface class BookSearch implements DataRepository<Book, int> {
  Future<List<Book>> findByTitleContainingIgnoreCase(String text);
  Future<int> countByYear(int year);
}
```

## The bean

- The bean's name is the interface's name with a lower-case first letter (`bookRepository`). `@Repository('books')` on the interface names it.
- A repository is checked at startup for what the build cannot know: its store and data source exist, its entity maps, the `${property}` placeholders and runtime expressions of its `@Query` texts resolve.
- The generated class extends `SimpleRepository` (the CRUD, sorting and paging methods) and writes only what the interface declares: a constant `PartTree` and one call for each derived query, a constant `QueryMethod` for each `@Query` method.

## Stores and databases

| Annotation | Meaning |
|---|---|
| none | The store of `spring.data.store` when it is set; else the `jdbc` store on the primary data source when `spring.datasource.url` is set, else the `memory` store. |
| `@UseStore('memory')` | Keep this repository's data in memory (tests, prototypes, caches). |
| `@UseStore('jdbc')` | A SQL database (SQLite, PostgreSQL). |
| `@UseDataSource('stats')` | The database of `spring.datasources.stats.*` (see [Data sources](data-sources.md)). |

```dart
@UseDataSource('stats')
abstract interface class VisitRepository implements ListCrudRepository<Visit, int> {}
```

The in-memory store has transactions, row locks (read committed, with deadlock detection), foreign keys and unique keys. Its wait for a row lock is `spring.data.memory.lock-timeout` (10 seconds by default).

## What the build checks

Every problem of an interface is one build error, listed with the others:

- a derived query name the entity does not support, with a suggestion (`findByTitel`);
- the number and types of parameters of a derived query;
- the return type: a `Future` or a `Stream`;
- the SQL, parameters and expressions of each `@Query` (see [@Query](query.md)).

## In Spring (Java)

```java
interface BookRepository extends ListCrudRepository<Book, Long> {
  List<Book> findByTitle(String title);
}
```

The interfaces have the same names, except `DataRepository` (Spring's `Repository`: here `@Repository` is the stereotype annotation). Every method returns a `Future` or a `Stream`; `findById` returns a nullable value instead of an `Optional`; `deleteAll(Iterable)` is `deleteAllOf`, `findAll(Sort)` is `findAllSorted` and `findAll(Pageable)` is `findAllPaged`.

## See also

- [Derived queries](derived-queries.md)
- [Paging and sorting](paging-and-sorting.md)
- [@Query](query.md)
