
# Entities

An entity is a Dart class marked `@Table`: the root of an aggregate, stored in one table. Each property is a column. The generator describes the class at build time, so the repositories read its properties and call its constructor without reflection.

## Why

In Spring Data JDBC's model an aggregate is a unit: it is loaded whole, saved whole and deleted whole, with its children. Other aggregates are referenced by id, never loaded with it. This keeps the mapping predictable: there is no lazy loading, no session that tracks changes and no proxy around your objects. What you hold is a plain Dart object, and `save` writes it at once.

## Example

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

enum Format { hardcover, paperback, ebook }

@Table('books')                 // without a value: the class name in snake case
class Book {
  Book({this.id, required this.title, this.format = Format.paperback});

  @Id()
  int? id;                      // null: new; the database gives the id

  String title;                 // column "title"

  @Column('pub_year')
  int? year;                    // column "pub_year" instead of "year"

  Format format;                // stored as the enum's name, as TEXT

  @Transient()
  bool selected = false;        // never written, never read

  @Version()
  int version = 0;              // raised at each save; 0 means not saved yet
}
```

## The annotations

| Annotation | On | What it does |
|---|---|---|
| `@Table([name, schema])` | class | The class is an aggregate root (or a child) stored in table `name`, by default the class name in snake case (`OrderLine` → `order_line`); `schema` is the table's schema, by default the connection's. |
| `@Id()` | property | The aggregate's id. A null id means new: `save` inserts and the store sets the generated id on the returned entity. |
| `@Column(name)` | property | The column's name, when it is not the property's name in snake case (`createdAt` → `created_at`). |
| `@Transient()` | property | Not stored: neither written nor read, it keeps the value the constructor gives it. |
| `@Version()` | property | Optimistic locking: an `int` or `DateTime` raised at each save (see [Locks](locks.md)). |
| `@MappedCollection(idColumn:, keyColumn:)` | property | A `List`, `Set` or `Map` of child entities saved, loaded and deleted with the root. |
| `@CreatedDate()`, `@LastModifiedDate()`, `@CreatedBy()`, `@LastModifiedBy()` | property | Audit values set on save (see [Auditing](auditing.md)). |
| `@Reference(Type)`, `@OnDelete(action)` | property | A reference to another aggregate by id (see [References and keys](references.md)). |
| `@Unique()`, `@UniqueConstraint([...], name:)` | property, class | Unique values (see [References and keys](references.md)). |

## Names

The default naming strategy writes every name in snake case:

| Dart | Database |
|---|---|
| class `OrderLine` | table `order_line` |
| property `createdAt` | column `created_at` |
| class `HTTPRequest` | table `http_request` (an acronym is one word) |
| property `line2Item` | column `line2_item` (a digit stays with the word before it) |

An annotation's value always wins, as written. To change a rule for the whole application, extend `NamingStrategy`, override a method (`tableName`, `columnName`, and the two of mapped collections) and declare it as a bean. A `NamingStrategy` bean of your own hides the derived names from the build's check of `@Query` texts (see [@Query](query.md)).

## Types

| Dart type | SQLite | PostgreSQL |
|---|---|---|
| `int` | `INTEGER` | `BIGINT` |
| `bool` | `INTEGER` (0 or 1) | `BOOLEAN` |
| `double`, `num` | `REAL` | `DOUBLE PRECISION` |
| `String` | `TEXT` | `TEXT` |
| an enum | `TEXT` (its name) | `TEXT` (its name) |
| `DateTime` | ISO 8601 `TEXT` in UTC | `TIMESTAMPTZ` (read back in UTC) |
| `Uint8List`, `List<int>` | `BLOB` | `BYTEA` |
| `BigInt` | `TEXT` | `NUMERIC` |
| `AggregateReference<T, ID>` | the id's type | the id's type |
| a class, a `Map`, a `List` or a `Set` with [`@Json`](json-columns.md) | JSON in `TEXT` | `JSONB` or `JSON` |

A nullable Dart type is a nullable column; a non-nullable one is `NOT NULL` in a schema the starter creates, and checked by `spring.data.jdbc.schema=validate`.

A `Map`, a `List` or a `Set` is no column by itself: mark it [`@Json`](json-columns.md), or [`@MappedCollection`](#children-mappedcollection) for rows of a child table. Without either, a SQL store refuses the property at build time or when the application starts, with the fix (see [JSON columns](json-columns.md#a-map-or-a-list-without-json)).

## Immutable entities

Fields may be `final`. The repository then builds a copy through the constructor where it has to change a value (the generated id, the new version, audit values), so always use the entity that `save` returns:

```dart
@Table('accounts')
class Account {
  const Account({required this.iban, required this.owner, this.version = 0});

  @Id()
  final String iban;        // an id you give yourself...

  final String owner;

  @Version()
  final int version;        // ...needs a version: 0 tells save to insert
}

final saved = await accounts.save(const Account(iban: 'DE89', owner: 'Ada'));
print(saved.version); // 1
```

An id the application gives itself (a UUID, a natural key) needs a `@Version`: without one, a non-null id means "existing", and `save` would try an update and throw an `IncorrectUpdateSemanticsDataAccessException` when no row matches.

## Children: @MappedCollection

```dart
@Table('orders')
class PurchaseOrder {
  PurchaseOrder({required this.customer, this.id, this.lines = const [], this.notes = const {}});

  @Id()
  int? id;

  String customer;

  @MappedCollection()
  List<OrderLine> lines;            // table order_lines: orders_id, orders_key (the position)

  @MappedCollection(idColumn: 'order_id', keyColumn: 'topic')
  Map<String, OrderNote> notes;     // table order_notes: order_id, topic (the key)
}

@Table('order_lines')               // a child takes @Table for its table's name
class OrderLine {
  OrderLine({required this.sku, required this.quantity});

  String sku;
  int quantity;
}

@Table('order_notes')
class OrderNote {
  OrderNote({required this.text});

  String text;
}
```

- The child table holds `idColumn`, which references the root's id: by default the root's table name followed by `_id`.
- A `List` or a `Map` also needs `keyColumn`, the position or the key: by default the root's table name followed by `_key`. A `Set` has none.
- A save writes the children again: the old rows are deleted and the current ones inserted, as in Spring Data JDBC.
- The children are covered by the root's `@Version`.
- A child cannot be saved or loaded alone, and it has no repository.

A property whose type is another entity without `@MappedCollection` (`Author author;`) is a mapping error with a hint. In Spring Data JDBC it would be a child; the starter never guesses whether you meant a child or a reference.

## New or existing

`save` inserts a new entity and updates an existing one. The rule is Spring Data's:

| The entity has | It is new when |
|---|---|
| a `@Version` of type `int` (non-nullable) | the version is `0` |
| a `@Version` of type `int?` | the version is `null` (a row stored at version `0` is updated, not inserted again) |
| a `@Version` of type `DateTime?` | the version is `null` |
| no `@Version`, an `@Id` | the id is `null` |
| neither | it cannot be saved: a `MappingException` |

## In Spring (Java)

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

The annotations have the same names and meanings. `@Unique` and `@UniqueConstraint` come from JPA's names, `@Reference` and `@OnDelete` are additions (Spring Data JDBC leaves the schema to you).

## See also

- [References and keys](references.md)
- [Repositories](repositories.md)
- [Schema and migrations](schema.md)
