# fall_data **Repository Path**: fall-flutter/fall_data ## Basic Information - **Project Name**: fall_data - **Description**: 封装数据库的链接及事务管理 - **Primary Language**: Dart - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2025-08-23 - **Last Updated**: 2025-10-26 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Fall Data 基于 SQLite 的数据库操作封装库,为 Flutter 应用提供类似 Spring Data 的数据访问层。 ## 特性 - 🎯 **类型安全的泛型DAO支持** - 基于 `BaseDao` 的泛型数据访问层 - 📝 **实体类注解映射** - 使用注解定义数据库表和字段映射 - 🔍 **流畅的查询构建器** - 链式调用的 SQL 查询构建 - 📄 **强大的分页查询** - 内置分页支持,类似 Spring Data 的 `Page` - 🔄 **完整的事务管理** - 支持声明式和编程式事务 - ⚡ **高性能的连接池** - 单例模式的数据库连接管理 - 🛠️ **丰富的工具类** - SQL 生成、类型转换、反射工具等 ## 安装 在 `pubspec.yaml` 中添加依赖: ```yaml dependencies: fall_data: ^1.0.0 ``` 然后运行: ```bash flutter pub get ``` ## 快速开始 ### 1. 初始化数据库 ```dart import 'package:fall_data/fall_data.dart'; void main() async { // 初始化数据库 await initializeFallData( databaseName: 'my_app.db', version: 1, enableLog: true, ); runApp(MyApp()); } ``` ### 2. 定义实体类 ```dart @Table('users') class User extends BaseEntity { @Column('name', nullable: false, length: 100) String? name; @Column('email', nullable: false, length: 255) @Unique() String? email; @Column('age', type: 'INTEGER') int? age; @Column('is_active', type: 'INTEGER', defaultValue: 1) bool isActive; User({this.name, this.email, this.age, this.isActive = true}); @override Map toMap() { // 实现实体转Map的逻辑 } @override void fromMap(Map map) { // 实现Map转实体的逻辑 } @override User copy() { // 实现实体复制的逻辑 } } ``` ### 3. 创建 DAO ```dart class UserDao extends BaseDao { @override String get tableName => 'users'; @override User createEntity() => User(); @override Map entityToMap(User entity) => entity.toMap(); @override User mapToEntity(Map map) { final user = User(); user.fromMap(map); return user; } // 自定义查询方法 Future findByEmail(String email) async { final condition = ConditionBuilder().eq('email', email); return findFirst(condition); } Future> findActiveUsers() async { final condition = ConditionBuilder() .eq('is_active', 1) .and(ConditionBuilder().notDeleted()); return findWhere(condition); } } ``` ### 4. 使用 DAO ```dart void main() async { final userDao = UserDao(); // 创建用户 final user = User( name: '张三', email: 'zhangsan@example.com', age: 25, ); // 保存用户 final savedUser = await userDao.save(user); print('保存成功: ${savedUser.id}'); // 查找用户 final foundUser = await userDao.findById(savedUser.id!); print('查找结果: ${foundUser?.name}'); // 更新用户 foundUser!.age = 26; await userDao.update(foundUser); // 分页查询 final pageable = PageRequest.withSort(1, 10, Sort.by('name')); final page = await userDao.findPage(pageable); print('分页结果: ${page.totalElements} 条数据'); } ``` ## 高级功能 ### 条件构建器 ```dart // 复杂条件查询 final condition = ConditionBuilder() .ge('age', 18) .and(ConditionBuilder() .like('name', '%张%') .or(ConditionBuilder().like('email', '%gmail%')) ) .and(ConditionBuilder().between('created_at', startDate, endDate)) .and(ConditionBuilder().notDeleted()); final users = await userDao.findWhere(condition); ``` ### 查询构建器 ```dart // 复杂 SQL 查询 final queryBuilder = QueryBuilder.table('users') .select(['name', 'email', 'age']) .innerJoin('orders', 'users.id = orders.user_id') .where('users.age >= ?', [18]) .groupBy(['users.id']) .having('COUNT(orders.id) > ?', [5]) .orderBy('users.created_at', ascending: false) .limit(20); final result = await userDao.findByQuery(queryBuilder); ``` ### 事务管理 ```dart // 编程式事务 await FallData.executeTransaction((txn) async { final user = await userDao.save(User(name: '事务用户')); final order = await orderDao.save(Order(userId: user.id)); // 如果这里抛出异常,整个事务会回滚 }); // 声明式事务(通过注解,需要 AOP 支持) class UserService { @Transactional() Future createUserWithProfile(User user, UserProfile profile) async { final savedUser = await userDao.save(user); profile.userId = savedUser.id; await profileDao.save(profile); return savedUser; } } ``` ### 分页查询 ```dart // 创建分页请求 final pageable = PageRequest.withSort( 1, // 页码(从1开始) 20, // 每页数量 Sort.by('name').andDesc('created_at'), // 排序 ); // 执行分页查询 final page = await userDao.findPage(pageable, condition); // 获取分页信息 print('当前页: ${page.number}'); print('每页大小: ${page.size}'); print('总数量: ${page.totalElements}'); print('总页数: ${page.totalPages}'); print('是否第一页: ${page.isFirst}'); print('是否最后一页: ${page.isLast}'); // 获取下一页的分页参数 final nextPageable = page.nextPageable; if (nextPageable != null) { final nextPage = await userDao.findPage(nextPageable, condition); } ``` ## 注解参考 ### 表注解 ```dart @Table('table_name', comment: '表注释') class MyEntity extends BaseEntity { // ... } ``` ### 字段注解 ```dart class User extends BaseEntity { @Id(autoIncrement: true) // 主键 @Column('id', type: 'INTEGER', nullable: false) int? id; @Column('name', nullable: false, length: 100, comment: '用户名') String? name; @Unique() // 唯一约束 String? email; @Index(name: 'idx_age') // 索引 int? age; @ForeignKey(table: 'roles', field: 'id') // 外键 int? roleId; @CreatedDate() // 自动设置创建时间 DateTime? createdAt; @LastModifiedDate() // 自动设置更新时间 DateTime? updatedAt; @Version() // 乐观锁版本控制 int version = 0; @SoftDelete() // 软删除标记 int deleted = 0; @JsonField() // JSON 字段序列化 Map? metadata; @Transient() // 忽略字段(不映射到数据库) String? tempField; } ``` ## API 文档 ### DatabaseManager - `initialize(DatabaseConfig)` - 初始化数据库 - `getDatabase([String?])` - 获取数据库实例 - `closeDatabase([String?])` - 关闭数据库 - `isInitialized([String?])` - 检查数据库是否已初始化 ### BaseDao #### 基础 CRUD - `save(T)` - 保存实体 - `saveAll(List)` - 批量保存 - `findById(int)` - 根据 ID 查找 - `findAll()` - 查找所有 - `update(T)` - 更新实体 - `delete(T)` - 删除实体 - `deleteById(int)` - 根据 ID 删除 #### 条件查询 - `findWhere(ConditionBuilder)` - 条件查询 - `findFirst([ConditionBuilder?])` - 查找第一个 - `count([ConditionBuilder?])` - 统计数量 - `exists(int)` - 检查是否存在 #### 分页查询 - `findPage(Pageable, [ConditionBuilder?])` - 分页查询 #### 软删除 - `softDelete(T)` - 软删除 - `softDeleteById(int)` - 根据 ID 软删除 - `restore(T)` - 恢复软删除 #### 事务和批处理 - `transaction(Function)` - 执行事务 - `batch(Function)` - 执行批处理 ### ConditionBuilder #### 比较操作符 - `eq(String, Object?)` - 等于 - `ne(String, Object?)` - 不等于 - `gt(String, Object?)` - 大于 - `ge(String, Object?)` - 大于等于 - `lt(String, Object?)` - 小于 - `le(String, Object?)` - 小于等于 #### 模糊查询 - `like(String, String)` - LIKE 查询 - `contains(String, String)` - 包含 - `startsWith(String, String)` - 以...开始 - `endsWith(String, String)` - 以...结束 #### 范围查询 - `between(String, Object?, Object?)` - 范围查询 - `inList(String, List)` - IN 查询 - `notInList(String, List)` - NOT IN 查询 #### NULL 判断 - `isNull(String)` - IS NULL - `isNotNull(String)` - IS NOT NULL #### 逻辑操作符 - `and(ConditionBuilder)` - AND - `or(ConditionBuilder)` - OR - `not()` - NOT ### QueryBuilder - `select(List)` - 选择字段 - `where(String, [List?])` - WHERE 条件 - `join(String, String)` - JOIN 连接 - `groupBy(List)` - GROUP BY - `having(String, [List?])` - HAVING - `orderBy(String, {bool})` - ORDER BY - `limit(int)` - LIMIT - `offset(int)` - OFFSET - `page(int, int)` - 分页 ## 贡献 欢迎提交 Issue 和 Pull Request! 1. Fork 本仓库 2. 创建特性分支 (`git checkout -b feature/AmazingFeature`) 3. 提交更改 (`git commit -m 'Add some AmazingFeature'`) 4. 推送到分支 (`git push origin feature/AmazingFeature`) 5. 创建 Pull Request ## 许可证 MIT License - 查看 [LICENSE](LICENSE) 文件了解详情。 ## 更新日志 ### v1.0.0 - 初始发布 - 支持基础 CRUD 操作 - 支持实体注解映射 - 支持查询构建器 - 支持分页查询 - 支持事务管理 - 支持软删除 - 提供丰富的工具类