Комментарии (2)
Ответ сгенерирован нейросетью и может содержать ошибки
Что такое entity?
Entity (сущность) - это объект, представляющий таблицу в базе данных или основную единицу в предметной области приложения. Entity содержит данные и отражает реальный объект.
Основные характеристики Entity
- Представляет таблицу в БД
- Имеет идентификатор (ID)
- Содержит бизнес-данные
- Может иметь методы
- Отражает реальный объект
Пример простой Entity
class User {
final String id; final String name; final String email; final DateTime createdAt; final bool isActive;
User({
required this.id,
required this.name,
required this.email,
required this.createdAt,
required this.isActive,
});
}
Entity с SQLite
class Product {
final int id; final String title; final String description; final double price; final int quantity;
Product({
required this.id,
required this.title,
required this.description,
required this.price,
required this.quantity,
});
Map toMap() {
return {
id: id,
title: title,
description: description,
price: price,
quantity: quantity,
};
}
factory Product.fromMap(Map map) {
return Product(
id: map[id],
title: map[title],
description: map[description],
price: map[price],
quantity: map[quantity],
);
}
}
Entity с Hive (локальное хранилище)
import package:hive/hive.dart;
part entity.g.dart;
HiveType(typeId: 0)
class Note {
@HiveField(0) late String id;
@HiveField(1) late String title;
@HiveField(2) late String content;
@HiveField(3) late DateTime createdAt;
}
Entity с relationships
class Author {
final String id; final String name; final List books;
Author({
required this.id,
required this.name,
required this.books,
});
}
class Book {
final String id; final String title; final Author author; final DateTime publishedAt;
Book({
required this.id,
required this.title,
required this.author,
required this.publishedAt,
});
}
Entity vs DTO
Entity:
- Представляет БД таблицу
- Может быть изменяемым
- Содержит идентификатор
- Используется в бизнес-логике
- Может быть связан с другими
DTO:
- Передача данных
- Только данные
- Неизменяемый
- Сериализуемый
- Не связан с БД
Как создать Entity из DTO
class UserEntity {
final String id; final String name; final String email;
UserEntity({
required this.id,
required this.name,
required this.email,
});
factory UserEntity.fromDTO(UserDTO dto) {
return UserEntity(
id: dto.id,
name: dto.name,
email: dto.email,
);
}
}
Базовая Entity для репозитория
class Post {
final String id; final String title; final String content; final String authorId; final DateTime createdAt; final DateTime updatedAt;
Post({
required this.id,
required this.title,
required this.content,
required this.authorId,
required this.createdAt,
required this.updatedAt,
});
Post copyWith({
String? title,
String? content,
}) {
return Post(
id: id,
title: title ?? this.title,
content: content ?? this.content,
authorId: authorId,
createdAt: createdAt,
updatedAt: DateTime.now(),
);
}
}
Когда использовать Entity
- Работа с БД
- Бизнес-логика
- Отношения между объектами
- Кеширование
- Состояние приложения
Лучшие практики
- Используйте final поля
- Добавьте ID для уникальности
- Используйте конструктор копирования
- Реализуйте методы сравнения
- Не смешивайте с DTO
Entity - это ключевой элемент архитектуры приложения, представляющий основные данные.