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; @Querymethods whose SQL, parameters and SpEL expressions are checked at build time, with "did you mean" suggestions;@Transactionalwith 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,NamedParameterJdbcTemplateandJdbcClientfor 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
# 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
// 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);
# lib/resources/application.properties
spring.datasource.url=sqlite:file:library.db
-- 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
);
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
jdbcstore whenspring.datasource.urlis set, and thememorystore 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=validateby default). A failure stops the start with its message. runApplicationAsyncis required with a SQL database. The synchronousrunApplication(args)fails at start with a report that says so.
What is inside
The model:
- Entities:
@Table,@Id,@Column,@Transient,@Version, children with@MappedCollection. - JSON columns:
@Json, a class, a list or a map in one column, and aMaporListwithout it on a SQL store. - References and keys:
AggregateReference,@Reference,@OnDelete,@Unique,@UniqueConstraint. - Auditing:
@CreatedDate,@LastModifiedByand@EnableDataAuditing.
Repositories:
- Repositories:
CrudRepositoryand friends,save, new or existing. - Derived queries:
findByTitleContaining,countBy,deleteBy,Top,OrderBy. - Paging and sorting:
Pageable,Sort,Page,Slice. - @Query: your own SQL,
@Modifying, entity placeholders, SpEL, and what the build checks. - Locks:
@Versionand@Lock. - Database functions:
@Procedure, a function called by name. - Changes of rows:
RowChange, a stream of changes, a result kept up to date. - Stores and their capabilities: what a store can do, and what a repository may use of it.
Transactions:
- Transactions:
@Transactional, propagation, isolation, rollback rules,TransactionTemplate.
Databases:
- Data sources: URLs, the pool, several databases, the beans.
- SQLite: files, in memory, an isolate of its own.
- PostgreSQL: URL parameters, TLS, types, errors.
- Schema and migrations: migrations,
schema.sql,spring.data.jdbc.schema. - JdbcTemplate and JdbcClient: plain SQL.
- Session hooks:
JdbcSessionHook, a role or a tenant for each transaction and statement. - Logging SQL:
show-sql, slow queries, masked values. - Errors: the
DataAccessExceptionhierarchy.
With other starters:
- In a web application:
Pageableparameters,PageJSON, 404, 409 and 400 answers. - Testing:
@DataTest, rollback,@Commit.
Reference:
- All properties: every key of the starter.
- Differences from Spring: what works differently than in Spring Data.
In Spring (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 (
FutureorStream). - Dart has no overloading:
findAll(),findAllSorted(Sort)andfindAllPaged(Pageable). - The repository is written by the build, and its derived queries and
@Querytexts are checked there, not at startup. - The full list is on Differences from Spring.