References and keys

Aggregates reference each other by id, never by holding the other object. There are two ways to write it: an AggregateReference<Author, int> property, or a plain int authorId marked @Reference(Author). Both become a foreign key in a schema the starter creates, and both are enforced the same way by the in-memory store.

Why

Holding the id instead of the object keeps each aggregate a unit: loading a book never loads its author, and saving a book never saves its author. You load the author with its own repository when you need it. The foreign key and @OnDelete then say what the database does when the author goes away, so the rule lives in one place instead of in every service.

Example

@Table('books')
@UniqueConstraint(['authorId', 'title'], name: 'uq_books_author_title')
class Book {
  Book({this.id, required this.title, required this.authorId, this.editor});

  @Id()
  int? id;

  String title;

  // A plain id: the type comes from Author's @Id and is checked at startup.
  // Derived queries (findByAuthorId) and @Query work on it as on any column.
  @Reference(Author)
  @OnDelete(OnDeleteAction.cascade)    // deleting an author deletes its books
  int authorId;

  // Or an AggregateReference; no @OnDelete means noAction.
  AggregateReference<Editor, int>? editor;
}

@Table('authors')
class Author {
  Author({this.id, required this.name});

  @Id()
  int? id;

  @Unique()                           // a second author of this name: DuplicateKeyException
  String name;
}
abstract interface class BookRepository implements ListCrudRepository<Book, int> {
  Future<List<Book>> findByAuthorId(int authorId);
  Future<List<Book>> findByEditor(AggregateReference<Editor, int> editor);
}

final books = await repository.findByEditor(const AggregateReference(7));
print(books.first.editor?.id); // 7

AggregateReference or @Reference

AggregateReference<Author, int> @Reference(Author) int authorId
Spring Data JDBC yes no (an addition)
The property's type the reference the id's type
Column the property's name in snake case (editor), or @Column the property's name in snake case (author_id), or @Column
Type check the ID type argument the property's type must be Author's @Id type (nullability aside), or the start fails naming both
Derived queries findByEditor(AggregateReference<Editor, int>) findByAuthorId(int)

The referenced class must be an aggregate root: a @Table class with an @Id.

@OnDelete

@OnDelete(OnDeleteAction.x) on a reference chooses what happens to the referencing rows when the referenced aggregate is deleted:

Action What happens
noAction The delete fails while rows reference it, checked when the statement ends. The default, also without @OnDelete.
restrict Like noAction, but checked at once, row by row: deleting rows that reference each other (a self-reference) may fail where noAction passes.
cascade The referencing aggregates are deleted too, and what references them, recursively.
setNull The referencing property is set to null. It must be nullable, or the start fails.
setDefault The referencing property is set to its default: the constant initializer of its field (int? publisherId = 1) or the constant default of its constructor parameter, written as the column's DEFAULT in a generated schema. A property without a default stops the start.

The database does it, not the repository. A cascade or a setNull goes through no delete or save of the repository, so no @Version is checked and auditing does not touch the affected rows (Hibernate's @OnDelete has the same limit). The in-memory store does the same, to behave like the database. Its cascades are recursive and run in the transaction, so a rollback undoes them.

@Unique and @UniqueConstraint

Dart cannot add a named unique: to @Column('x') (a positional parameter cannot be mixed with named ones), so uniqueness is an annotation of its own.

The schema

The in-memory store

The in-memory store behaves exactly like SQLite with foreign_keys = ON, so a test that passes in memory does not fail in production:

In Spring (Java)

@Table("books")
class Book {
  @Id Long id;
  String title;
  AggregateReference<Author, Long> author;
}

Spring Data JDBC has only AggregateReference and leaves foreign keys, cascades and unique constraints to your own schema. JPA's @ManyToOne is the closest to @Reference, without the object graph.

See also