
# 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

```dart
@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;
}
```

```dart
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

- `@Unique()` on a property: its values must be unique in its table. Several rows may hold null, as in SQL.
- `@UniqueConstraint(['authorId', 'title'], name: ...)` on the class: no two rows may hold the same values in all the listed properties (a row with a null among them never conflicts). The names are Dart property names, checked at startup. It is repeatable.
- Without a name, a constraint is `uq_<table>_<columns>`.
- A save that breaks one throws a `DuplicateKeyException`, from the database and from the in-memory store alike.

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

- With `spring.data.jdbc.schema=create`, every reference is a foreign key (`REFERENCES "authors"("id")`, with its `ON DELETE`) and gets an index on its column; `@Unique` and `@UniqueConstraint` are `UNIQUE` constraints. Foreign keys come after the tables, so references in a cycle work.
- With `spring.data.jdbc.schema=validate` (the default), an explicit `@OnDelete`, `@Unique` or `@UniqueConstraint` that the database does not have is an error. A reference without a foreign key is a warning: its integrity is not enforced.

## 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:

- a reference to a missing aggregate is a `DataIntegrityViolationException`;
- a delete follows the `@OnDelete`;
- a duplicate is a `DuplicateKeyException`;
- null references and null unique values are never checked.

## In Spring (Java)

```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

- [Entities](entities.md)
- [Schema and migrations](schema.md)
- [Errors](errors.md)
