Generate book entity adapter
Data Layer
Summary
This lesson demonstrates how to prepare an entity for persistence using the Hive NoSQL database by generating a type adapter. The instructor emphasizes why it is preferable to cache the BookEntity rather than the more complex BookModel, as entities represent simple data structures that are easier to serialize. By adding Hive-specific annotations like @HiveType and @HiveField, the instructor sets the stage for the build_runner package to automatically generate the necessary serialization adapter. This step is a critical prerequisite for implementing local data caching within the Clean Architecture data layer.
Key Ideas
- Hive caching requires an adapter to serialize custom objects.
- BookEntity is the preferred target for caching because it is simpler and contains only primitive types compared to the BookModel.
- @HiveType(typeId: 0) annotation identifies the class as a Hive-serializable type.
- @HiveField(index) annotation assigns a unique, non-negative integer to each class property for serialization mapping.
- part 'book_entity.g.dart'; directive is required to link the generated adapter code to the entity file.
- pub run build_runner build command triggers the code generation process.
Code Snippets
import 'package:hive/hive.dart';
part 'book_entity.g.dart';
@HiveType(typeId: 0)
class BookEntity {
@HiveField(0)
final String bookId;
@HiveField(1)
final String? image;
@HiveField(2)
final String title;
@HiveField(3)
final String? authorName;
@HiveField(4)
final num? price;
@HiveField(5)
final num? rating;
BookEntity({
required this.image,
required this.title,
required this.authorName,
required this.price,
required this.rating,
required this.bookId,
});
}My Notes
The decision to cache BookEntity instead of BookModel is a strong architectural choice that keeps the storage layer decoupled from API-specific model logic. By using build_runner, we maintain clean, generated code that avoids manual serialization boilerplate. [Editor's note] A critical gotcha to remember is that changing the order of @HiveField indices or deleting fields after the initial generation will break existing local data stored in Hive. If you must change the data structure significantly, you will need to perform a database migration or clear the local Hive storage to prevent deserialization errors.