
# spring_boot_starter_data

`spring_boot_starter_data` is the data layer of Spring for Dart, the Dart port of Spring Boot's `spring-boot-starter-data-jdbc`. You describe an aggregate with `@Table`, declare a repository interface, and the generator writes its implementation, derived queries included. The same repositories run in memory, on SQLite or on PostgreSQL, chosen by properties.

The model is Spring Data JDBC's, not JPA's: an aggregate is loaded and saved whole, `save` writes at once, and other aggregates are referenced by id. There is no persistence context, no lazy loading and no proxy of entities.

## Why

Most applications store the same kind of data the same way: a table per aggregate, a few finders, paging, a transaction around a business operation, migrations at startup. Written by hand, this is the same SQL and mapping code over and over. The starter gives you:

- repositories whose implementation the build writes, with `findByTitleContainingIgnoreCase`-style methods checked against the entity at build time;
- `@Query` methods whose SQL, parameters and SpEL expressions are checked at build time, with "did you mean" suggestions;
- `@Transactional` with Spring's seven propagations, isolation levels, timeouts, read-only and rollback rules, checked scenario by scenario against Spring itself on PostgreSQL;
- optimistic locking (`@Version`) and pessimistic locks (`@Lock`);
- references with foreign keys, `@OnDelete`, unique keys and auditing;
- migrations (Flyway's file naming), `schema.sql` / `data.sql`, and a schema check against the entities;
- `JdbcTemplate`, `NamedParameterJdbcTemplate` and `JdbcClient` for plain SQL;
- an in-memory store that behaves like SQLite with foreign keys on, for tests and prototypes;
- `@DataTest`, a test slice with an in-memory SQLite database and a rollback after every test.

No reflection is used at run time: the generator describes the entities and writes the repositories.

## Setup

```yaml
# pubspec.yaml
dependencies:
  spring_boot_starter_data: ^0.9.0
  sqlite3: ^3.8.0        # for sqlite: URLs; list postgres: ^3.5.0 for PostgreSQL

dev_dependencies:
  build_runner: ^2.17.0
  spring_core_dart_generator: ^0.9.0   # writes the repositories
  spring_boot_starter_test: ^0.9.0     # @DataTest
  test: ^1.33.0
```

The starter has no driver inside. You list the one you want (`sqlite3`, `postgres`, or both), and the generator writes a `JdbcDriver` bean for each driver package it finds. The URL's scheme chooses among them. Without any URL, repositories keep their data in memory.

One import is enough: `package:spring_boot_starter_data/spring_boot_starter_data.dart` also exports `spring_boot_starter_logging`, and through it `spring_boot_dart` and `spring_core_dart`.

## Example

```dart
// bin/main.dart
import 'package:spring_boot_starter_data/spring_boot_starter_data.dart';

import 'spring_gen/main.spring.dart';

@Table('books')
class Book {
  Book({this.id, required this.title, this.year});

  @Id()
  int? id;          // null: new, the database gives the id
  String title;
  int? year;

  @Version()
  int version = 0;  // optimistic locking; 0 means "not saved yet"
}

// No annotation needed: extending a repository interface is enough.
abstract interface class BookRepository
    implements
        ListCrudRepository<Book, int>,
        ListPagingAndSortingRepository<Book, int> {
  Future<List<Book>> findByTitleContainingIgnoreCase(String text);
  Future<Page<Book>> findByYearGreaterThan(int year, Pageable page);
  Future<int> countByYearBetween(int from, int to);
}

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

  final BookRepository books;

  // One transaction: both saves commit together, or neither does.
  @Transactional()
  Future<void> addSeries(List<String> titles) async {
    for (final title in titles) {
      await books.save(Book(title: title));
    }
  }
}

@SpringBootApplication()
// A SQL database is set up on a connection: start asynchronously.
Future<void> main(List<String> args) => runApplicationAsync(args);
```

```properties
# lib/resources/application.properties
spring.datasource.url=sqlite:file:library.db
```

```sql
-- lib/resources/db/migration/V1__books.sql
create table books (
  id integer primary key autoincrement,
  title text not null,
  year integer,
  version integer not null
);
```

```bash
dart run build_runner build   # writes the repository and the wiring
dart run bin/main.dart
```

At startup the migration runs, the starter checks that the `books` table fits the `Book` entity, and only then can any repository or `JdbcTemplate` use the database.

## Running it

What starts with the starter:

- **No `@EnableJdbcRepositories`.** Every interface of the scanned code that extends a repository interface becomes a bean.
- **The build checks the repositories.** A method name the entity does not support (`findByTitel`) is a build error: `No property 'titel' found for type 'Book'; did you mean 'title'?`.
- **The store is chosen for you.** Repositories use the `jdbc` store when `spring.datasource.url` is set, and the `memory` store otherwise. `@UseStore('memory')` and `@UseDataSource('stats')` choose per repository.
- **The schema is ready before any use.** Migrations and scripts run, then the entities are checked against the schema (`spring.data.jdbc.schema=validate` by default). A failure stops the start with its message.
- **`runApplicationAsync` is required with a SQL database.** The synchronous `runApplication(args)` fails at start with a report that says so.

## What is inside

The model:

- [Entities](entities.md): `@Table`, `@Id`, `@Column`, `@Transient`, `@Version`, children with `@MappedCollection`.
- [JSON columns](json-columns.md): `@Json`, a class, a list or a map in one column, and a `Map` or `List` without it on a SQL store.
- [References and keys](references.md): `AggregateReference`, `@Reference`, `@OnDelete`, `@Unique`, `@UniqueConstraint`.
- [Auditing](auditing.md): `@CreatedDate`, `@LastModifiedBy` and `@EnableDataAuditing`.

Repositories:

- [Repositories](repositories.md): `CrudRepository` and friends, `save`, new or existing.
- [Derived queries](derived-queries.md): `findByTitleContaining`, `countBy`, `deleteBy`, `Top`, `OrderBy`.
- [Paging and sorting](paging-and-sorting.md): `Pageable`, `Sort`, `Page`, `Slice`.
- [@Query](query.md): your own SQL, `@Modifying`, entity placeholders, SpEL, and what the build checks.
- [Locks](locks.md): `@Version` and `@Lock`.
- [Database functions](database-functions.md): `@Procedure`, a function called by name.
- [Changes of rows](changes.md): `RowChange`, a stream of changes, a result kept up to date.
- [Stores and their capabilities](stores.md): what a store can do, and what a repository may use of it.

Transactions:

- [Transactions](transactions.md): `@Transactional`, propagation, isolation, rollback rules, `TransactionTemplate`.

Databases:

- [Data sources](data-sources.md): URLs, the pool, several databases, the beans.
- [SQLite](sqlite.md): files, in memory, an isolate of its own.
- [PostgreSQL](postgresql.md): URL parameters, TLS, types, errors.
- [Schema and migrations](schema.md): migrations, `schema.sql`, `spring.data.jdbc.schema`.
- [JdbcTemplate and JdbcClient](jdbc.md): plain SQL.
- [Session hooks](session-hooks.md): `JdbcSessionHook`, a role or a tenant for each transaction and statement.
- [Logging SQL](logging.md): `show-sql`, slow queries, masked values.
- [Errors](errors.md): the `DataAccessException` hierarchy.

With other starters:

- [In a web application](web.md): `Pageable` parameters, `Page` JSON, 404, 409 and 400 answers.
- [Testing](testing.md): `@DataTest`, rollback, `@Commit`.

Reference:

- [All properties](properties.md): every key of the starter.
- [Differences from Spring](differences.md): what works differently than in Spring Data.

## In Spring (Java)

```java
@Table("books")
class Book {
  @Id Long id;
  String title;
  Integer year;
  @Version long version;
}

interface BookRepository
    extends ListCrudRepository<Book, Long>, ListPagingAndSortingRepository<Book, Long> {
  List<Book> findByTitleContainingIgnoreCase(String text);
  Page<Book> findByYearGreaterThan(int year, Pageable page);
}
```

Differences that matter:

- Every repository method is asynchronous (`Future` or `Stream`).
- Dart has no overloading: `findAll()`, `findAllSorted(Sort)` and `findAllPaged(Pageable)`.
- The repository is written by the build, and its derived queries and `@Query` texts are checked there, not at startup.
- The full list is on [Differences from Spring](differences.md).

## See also

- [spring_core_dart](../spring-core-dart/index.md)
- [spring_boot_starter_web](../spring-boot-starter-web/index.md)
- [The generator and data](../spring-core-dart-generator/data.md)
- [spring_boot_starter_supabase](../spring-boot-starter-supabase/index.md)
- [What a build contains](optimizations.md)
