データ: エンティティ、リポジトリ、クエリ

spring_boot_starter_data を使うアプリケーションに対して、ジェネレーターは Spring Data がアプリケーションの起動時に行う作業を行います。エンティティを読み、リポジトリのインターフェースを実装し、派生クエリメソッドの名前を解析し、@Query のテキストをチェックします。そのすべてがビルド時に行われるので、アプリの起動時に解析や記述は何も行われず、綴りを間違えたプロパティは起動時の失敗ではなく、提案付きのビルドエラーになります。

データスターターのアノテーションは URL で照合されるので、ジェネレーターはスターターに依存しません。

使う理由

Spring Data は実行時に動的プロキシでリポジトリの実装を作り、起動のたびに findByTitleAndYear のようなメソッド名を解析します。Dart は実行時にクラスを作れず、起動時の解析はモバイルアプリの起動のたびに時間を食います。ビルドはすでにエンティティ、インターフェース、lib/resources/ の SQL ファイルを見ているので、実装を書き、すべてをエンティティに対してチェックし、インターフェースのすべての問題を一度に報告できます。

エンティティ: EntityIntrospection

各 @Table クラスと、@Query メソッドが返す各クラス (DTO) に対して、ジェネレーターは EntityIntrospection を書き出します。定数としてのプロパティと、一つのプロパティを読む、コンストラクターを呼ぶ、一つのプロパティを設定するクロージャーです。それ以上はありません。

入力:

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

  @Id()
  int? id;

  String name;

  @Unique()
  String? isni;
}

出力 (ジェネレーターのテストから。プレフィックスは外しています):

EntityIntrospection<Author>(
  r'Author',
  const [
    EntityProperty(r'id', ClassType<int>(nullable: true),
        annotations: [Id()], parameter: true, writable: true),
    EntityProperty(r'name', ClassType<String>(),
        parameter: true, writable: true),
    EntityProperty(r'isni', ClassType<String>(nullable: true),
        annotations: [Unique()], parameter: true, writable: true),
  ],
  annotations: const [Table(r'authors')],
  get: (e, i) => switch (i) {
    0 => e.id,
    1 => e.name,
    _ => e.isni,
  },
  create: (v) => Author(
      name: v[1] as String, id: v[0] as int?, isni: v[2] as String?),
  write: (e, i, v) => switch (i) {
    0 => e.id = v as int?,
    1 => e.name = v as String,
    2 => e.isni = v as String?,
    _ => null,
  },
)

モジュールのすべての記述は、データ層が読む一つの Bean entityIntrospections#<module> (EntityIntrospections) にまとめられます。エンティティのないモジュールにはこれがありません。

@Table クラスは、@Introspected でもない限り、Introspection (JSON と SpEL が使う一般的な記述) を 受け取りません。データ層に必要なのは EntityIntrospection だけです。

エンティティのエラー

データ層がクラスを生成したり値を入れたりできない場合、ビルドは失敗します。

問題 メッセージ (一部)
どのフィールドも指さない必須のコンストラクターパラメーター (Book(String isbn)) Book(isbn) を示し、names no field と伝え、this.isbn を提案する
public な無名コンストラクターがない @Table class Book has no public unnamed constructor ... と Add one
private なクラス @Table class _Book must be public ...
抽象クラス @Table class Book is abstract ...。具象クラスを求める

どのフィールドも指さない省略可能なパラメーターは create から除外されます。

リポジトリ: SimpleRepository を継承するクラス

DataRepository を (直接、または CrudRepository、ListCrudRepository などを通して) 継承する各インターフェースに対して、ジェネレーターはクラスを書き出します。それは CRUD メソッドを持つスターターの SimpleRepository を継承し、インターフェースのその他のメソッドごとに一行を追加します。スターターが起動時に読むためにメソッドを記述するものはありません。

入力:

abstract interface class BookRepository
    implements ListCrudRepository<Book, int> {
  Future<List<Book>> findByTitleAndYear(String title, int year);

  @Query('select title from books where year = :year')
  Future<List<BookCard>> cards(int year);
}

出力 (プレフィックスは外しています):

class _$BookRepositoryImpl extends SimpleRepository<Book, int>
    implements BookRepository {
  _$BookRepositoryImpl(super.operations);

  static _$BookRepositoryImpl $create(DependencyResolver r) =>
      _$BookRepositoryImpl(r
          .dependency<RepositoryFactory>()
          .operations<Book, int>(r'BookRepository', queries: [_cards]));

  static const _findByTitleAndYear = PartTree(r'findByTitleAndYear', [
    OrPart([Part(r'title'), Part(r'year')]),
  ]);

  static const _cards = QueryMethod(
    r'cards',
    Query(r'select title from books where year = :year'),
    parameters: [r'year'],
    element: ClassType<BookCard>(),
  );

  @override
  Future<List<Book>> findByTitleAndYear(String title, int year) =>
      this.operations.list(_findByTitleAndYear, [title, year]);

  @override
  Future<List<BookCard>> cards(int year) =>
      this.operations.query<List<BookCard>>(_cards, [year]);
}

Bean 定義はインターフェースとそのスーパータイプを create: (r) => _$BookRepositoryImpl.$create(r) で登録します。Bean 名はインターフェース名の先頭を小文字にしたもの (bookRepository)、または @Repository('library') で与えた名前です。インターフェースのアノテーション (@Repository、@UseStore) は operations に渡されます。

CRUD メソッドだけのリポジトリは空のクラスを受け取ります。インターフェースが再宣言した CRUD メソッドは SimpleRepository に任されます。ジェネリックな基底インターフェース (interface Crud<E> extends DataRepository<E, int>) は Bean にならず、具象の @Repository クラスは普通のコンポーネントのままです。

派生クエリ: 定数の PartTree

名前が find、read、get、query、search、stream、count、exists、delete、remove で始まり、任意で単語が続き、その後に By が来るメソッドは派生クエリです。ビルドは Spring Data の PartTree と同じように名前を読み (Distinct、First/Top<n>、And、Or、演算子、IgnoreCase、AllIgnoreCase、OrderBy...Asc/Desc)、結果を定数として書き出します。

static const _findByTitleContaining = PartTree(r'findByTitleContaining', [
  OrPart([Part(r'title', PartType.containing)]),
]);

操作はメソッドの戻り値の型に従います。

戻り値の型 呼び出し
Future<List<Book>>、Future<Iterable<Book>> list
Future<Set<Book>> set
Future<Book?> one
Future<Book> single
Stream<Book> stream
Future<Page<Book>> (Pageable パラメーター付き) page
Future<Slice<Book>> (Pageable パラメーター付き) slice
countBy... からの Future<int> countBy
existsBy... からの Future<bool> existsBy
deleteBy... / removeBy... からの Future<int> または Future<void> deleteBy
deleteBy... からの Future<List<Book>> deleteByReturning

Sort と Pageable のパラメーターは名前で渡され (sort: order)、@Lock は呼び出しと一緒に渡されます。

派生クエリのエラー

ビルドは各名前を、エンティティ、パラメーター、戻り値の型と照合します。間違った名前、未知のプロパティ、コレクションや入れ子のパスであるプロパティ、合わないパラメーターはビルドを失敗させます。一つのインターフェースのすべての問題は一つのエラーにまとめられ、メソッドの順に、メソッドごとに一行です。

Invalid repository BookRepository:
  - BookRepository.findByTitel: No property 'titel' found for type 'Book'; did you mean 'title'? Available properties: id, title, year.
  - BookRepository.findAll: not a CRUD method of the repository interfaces and not a derived query
  - BookRepository.twice has a body: every method of the interface is implemented by the generated class.

@Query メソッド

@Query を持つメソッドは、小さな QueryMethod 定数として書かれます。ビルドは書き出す前に、メソッドとそのテキストをチェックします。

メソッドとそのアノテーション。 メッセージの一部:

メソッド メッセージ (BookRepository.<method>: の後)
@Query('select * from books') Future<void> voidRead(); the method returns nothing: a change needs @Modifying, a read a result type
@Modifying() ... Future<String> modifyingText(); @Modifying returns the rows changed (Future<int>), whether any changed (Future<bool>) or nothing (Future<void>), not String
... Future<Page<Book>> pageAlone(); a page needs a Pageable parameter (the window to read)
Page を返さないメソッドの countQuery: countQuery is for a method that returns a Page
... Future<Map<String, int>> intMap(); a row as a map is a Map<String, Object?>, not Map<String, int>
private な rowMapper the rowMapper of @Query must be public: the generated code refers to it

テキストのパラメーターとプレースホルダー。

テキスト メッセージ (BookRepository.<method>: の後)
... where year = :yeer (パラメーター year) :yeer matches no parameter of the method (it has year)
... where year = :book.year :book.year matches no parameter of the method (it has book) (to read a property write :#{#book.year})
... where year = ? the query has a plain ? marker: write :name and bind it by the name of a parameter of the method
select * from #{#tableName} ... #{#tableName} is not allowed in the SQL text: only #{#entityName} is; to bind a value write :#{#tableName}
select * from {Bok} {Bok}: no @Table class Bok in the application, did you mean 'Book'?
select {Book.titel} from {Book} {Book.titel}: Book has no property titel, did you mean 'title'? (stored properties: id, title, year, authorId)
select {Book.cache} from {Book} {Book.cache}: Book.cache is @Transient: it has no column

countQuery も同じようにチェックされ、BookRepository.counted (countQuery): ... のように名前が付きます。エンティティのプレースホルダーは定数の一部になります: entities: {r'Book': Book}。

テーブルとカラム。 ビルドは lib/resources/ のマイグレーションと初期化スクリプトからスキーマを知ります。それらはスターターが見つけるのと同じように見つけられます (spring.sql.migration.locations、デフォルトは resources:db/migration。spring.sql.init.schema-locations)。SQL ファイルがなければ、エンティティがスキーマです。綴りを間違えたテーブルやカラムは、既知の名前が近い場合にビルドを失敗させます。

  - BookRepository.column: b.titel: no column titel in books, did you mean 'title'?
  - BookRepository.table: bokks: no table bokks, did you mean 'books'?

ビルドがスキーマに確信を持てない場合、このチェックは自動的に無効になります。lib/resources/ の外やプレースホルダー付きの場所、場所を変えうるプロファイルのファイルやインポート、解析できないファイル、カラムに別の名前を付けうるアプリケーションの NamingStrategy Bean です。

@Query の中の SpEL: Dart にコンパイル

@Query テキストの中の :#{...} の値は SpEL 式です。ビルドは可能な場合、パラメーターの型に対してチェックしたうえで、式を Dart にコンパイルします。

@Query('select * from books where title = :#{#book.title}')
Future<List<Book>> sameTitle(Book book);
static final _sameTitle = QueryMethod(
  r'sameTitle',
  const Query(r'select * from books where title = :#{#book.title}'),
  parameters: const [r'book'],
  element: const ClassType<Book>(),
  expressions: [(arguments, context) => (arguments[0] as Book).title],
);

コンパイルされた式は関数なので、QueryMethod は static const ではなく static final になります。コンパイラーが扱えるのは、名前による引数 (#book)、位置による引数 (#p1、#a0、[0])、コンテキストの #entityName と #methodName、アプリケーションの Bean (@cutoffs.year は context.bean(r'cutoffs') に対する型付きの呼び出しになります)、環境 (@environment.getProperty('c', '0')) です。

式の間違いはビルドエラーです。

式 メッセージ (BookRepository.<method>: the expression :#{...} is invalid: の後)
#book.titel No property 'titel' on type 'Book'; did you mean 'title'?
#yeer Unknown variable '#yeer'; did you mean '#year'?
1 + Invalid expression: EL1042E...
#book.title.substring() Method 'String.substring' takes between 1 and 2 arguments, but 0 were given
#book?.title.length Cannot read property 'length' on String?

コンパイラーが扱えないもの (T(String).valueOf(...) の呼び出し、${property} プレースホルダーを含むテキスト) は、実行時の SpEL インタープリターに任されます。expressions のそのエントリーは null です。その場合、そのような式が到達するクラスと、そのメソッドを呼ぶ Bean は、インタープリターが必要とする Introspection を受け取ります (実行されるものだけ を参照)。エンティティがそれを受け取ることはありません。

@Procedure、watch…By、changes…By

@Procedure('name') の付いたメソッド (データベース関数) は、ProcedureMethod の定数と、operations.procedure<R> の呼び出し (Stream では operations.procedureStream<E>) として書かれます。

static const _over = ProcedureMethod(
  r'over',
  Procedure(r'books_over'),
  parameters: [r'minYear'],
  element: ClassType<Book>(),
);

@override
Future<List<Book>> over(int minYear) =>
    this.operations.procedure<List<Book>>(_over, [minYear]);

その行から作られるクラスは、@Query のものと同じように記述されます。ビルドは、Page や Slice の結果、Pageable や Sort のパラメーター、空の関数名、そして @Query、@Modifying、@Lock と一緒の @Procedure を拒否します。

行の変更を報告するストアのために、二つのプレフィックスが find と同じように派生されます。watch…By (Stream<List<T>>、operations.watch の呼び出し) と changes…By (Stream<RowChange<T>>、operations.changes の呼び出し) です。それ以外の戻り値の型は、期待される型を示すビルドエラーです。changes…By の名前に書けるのは条件だけです。

メソッドがストアに必要とするもの

生成されたクラスは、各メソッドがストアに必要とするものを、StoreRequirement としてリポジトリの操作に伝えます。@Lock (locks)、@Query (queries)、@Procedure (functions)、watch または changes のメソッド (changes)、メソッドの @Transactional (transactions) です。

operations<Book, int>(
  r'Ledger',
  annotations: const [UseStore(r'jdbc')],
  functions: [_over],
  requirements: const [
    StoreRequirement(r'over', DataStoreCapability.functions),
    StoreRequirement(r'findByIsbn', DataStoreCapability.transactions),
  ],
)

ランタイムは、リポジトリが作成されるときに、それをストアと比較します。ビルドは、ストアを知っている場合、それをより早く行います。アプリケーションの依存関係の lib/spring_auto_configuration.dart が宣言またはエクスポートする @DataStoreDeclaration の定数を読み、リポジトリのストアを、その @UseStore、@UseDataSource (SQL のストア)、application.yml または application.properties (プロファイルなし) の spring.data.store、または defaultWhen が成り立つ最初の記述されたストアから判断します。そのとき、ストアにない機能はリポジトリの問題の一つになり、トランザクションなしと記述されたデフォルトのストアでの @Transactional の Bean (transactionManager: なし) はビルドを失敗させます。何も記述していないストアは、ランタイムに任されます。

アップグレードの後は、リポジトリを生成し直す必要があります。生成されたクラスが requirements: を渡すためです。

DataStoreDescriptor(collectionsNeedJson: true) で記述されたストア (SQL のストア) では、ビルドはリポジトリのエンティティと、そのマッピングされたコレクションの子もチェックします。@Json も @MappedCollection もない Map、Set、そして単純な値以外の List は、直し方とともに、リポジトリの問題の一つになります (Parcel.meta: a Map<String, Object?> property without @Json has no column on a SQL store: add @Json() to keep it as JSON, or @MappedCollection for rows of a child table)。単純な値のリストはストアに任されます。ストアは、それを配列の列に保持できるかもしれません。

関連項目