# genericrdb **Repository Path**: qiuyu123/genericrdb ## Basic Information - **Project Name**: genericrdb - **Description**: No description available - **Primary Language**: Unknown - **License**: MulanPSL-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 0 - **Created**: 2026-01-16 - **Last Updated**: 2026-01-16 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # GenericRdbHelper - HarmonyOS 数据库ORM工具 (ArkTS版) ## 简介 `GenericRdbHelper` 是一个为 HarmonyOS 应用开发的轻量级 ORM 工具类,**完全符合 ArkTS 规范**,不使用 `any` 类型、装饰器等 TypeScript 特性。 ## 主要特性 - **ArkTS 兼容**: 完全符合 ArkTS 编译器规范 - **接口驱动**: 通过实现 `IEntity` 接口定义表结构 - **类型安全**: 使用明确的类型定义,无 `any` 类型 - **完整的 CRUD**: 支持增删改查、批量操作、条件查询等 - **自动建表**: 根据 Model 配置自动创建数据库表 - **工厂模式**: 使用工厂函数创建实体实例 ## 核心文件 ``` entry/src/main/ets/ ├── db/ │ ├── decorators/ │ │ └── DbDecorators.ets # 元数据定义(TableConfig, ColumnConfig, IEntity) │ ├── GenericRdbHelper.ets # 通用数据库助手 │ └── SdkRdbHelper.ets # 旧版工具类 ├── model/ │ ├── UserInfo.ets # 用户信息实体 │ ├── Product.ets # 商品信息实体 │ └── Order.ets # 订单信息实体 └── examples/ └── RdbHelperExample.ets # 使用示例 ``` ## 快速开始 ### 1. 定义 Model 类 Model 类需要实现 `IEntity` 接口: ```typescript import { TableConfig, IEntity } from '../db/decorators/DbDecorators'; export class UserInfo implements IEntity { public id: number = 0; public username: string = ''; public password: string = ''; public email: string = ''; public age: number = 0; private static tableConfig: TableConfig | null = null; constructor() {} // 定义表结构 getTableConfig(): TableConfig { if (UserInfo.tableConfig === null) { UserInfo.tableConfig = new TableConfig('user_info') .addPrimaryKey('id', 'id', true) .addTextColumn('username', 'username', true) .addTextColumn('password', 'password', true) .addTextColumn('email', 'email', false) .addIntColumn('age', 'age', false); } return UserInfo.tableConfig; } // 转换为值映射 toValueMap(): Map { const map = new Map(); if (this.id > 0) map.set('id', this.id); map.set('username', this.username); map.set('password', this.password); map.set('email', this.email); map.set('age', this.age); return map; } // 从值映射填充 fromValueMap(map: Map): void { const idVal = map.get('id'); if (idVal !== null && idVal !== undefined) { this.id = idVal as number; } // ... 其他字段类似 } // 工厂方法 static createInstance(): UserInfo { return new UserInfo(); } } ``` ### 2. 创建数据库助手 ```typescript import { GenericRdbHelper } from '../db/GenericRdbHelper'; import { UserInfo } from '../model/UserInfo'; // 创建模板实例和工厂函数 const templateUser = new UserInfo(); const userHelper = new GenericRdbHelper( templateUser, () => UserInfo.createInstance() ); // 初始化数据库 (自动创建表) await userHelper.initRdbStore(getContext(), 'my_app.db'); ``` ### 3. 执行 CRUD 操作 ```typescript // 插入 const user = new UserInfo(); user.username = '张三'; user.password = '123456'; const rowId = await userHelper.insert(user); // 查询所有 const entities = await userHelper.queryAll(); for (let i = 0; i < entities.length; i++) { const user = entities[i] as UserInfo; console.log(user.username); } // 根据主键查询 const entity = await userHelper.queryByPrimaryKey(1); if (entity) { const user = entity as UserInfo; console.log(user.username); } // 更新 user.age = 26; await userHelper.update(user, 'id', '1'); // 删除 await userHelper.deleteByPrimaryKey(1); ``` ## API 参考 ### TableConfig 方法 | 方法 | 说明 | |------|------| | `addPrimaryKey(propertyName, columnName, autoIncrement)` | 添加主键列 | | `addTextColumn(propertyName, columnName, notNull)` | 添加文本列 | | `addIntColumn(propertyName, columnName, notNull, defaultValue)` | 添加整数列 | | `addRealColumn(propertyName, columnName, notNull, defaultValue)` | 添加浮点列 | ### GenericRdbHelper 方法 | 方法 | 说明 | |------|------| | `initRdbStore(context, dbName)` | 初始化数据库 | | `insert(entity)` | 插入单条记录 | | `batchInsert(entities)` | 批量插入 | | `update(entity, whereColumn, whereValue)` | 更新记录 | | `insertOrUpdate(entity)` | 插入或更新 | | `queryAll()` | 查询所有记录 | | `query(whereColumn, whereValue)` | 条件查询 | | `queryByPrimaryKey(value)` | 根据主键查询 | | `querySql(sql, args)` | 自定义SQL查询 | | `delete(whereColumn, whereValue)` | 删除记录 | | `deleteByPrimaryKey(value)` | 根据主键删除 | | `deleteAll()` | 删除所有记录 | | `exists(columnName, value)` | 检查是否存在 | | `count()` | 获取记录总数 | | `close()` | 关闭数据库连接 | ## 注意事项 1. **实现 IEntity 接口**: Model 类必须实现 `IEntity` 接口的三个方法 2. **工厂方法**: 必须提供静态工厂方法用于创建实例 3. **类型转换**: 查询结果需要手动转换为具体类型 (`entity as UserInfo`) 4. **错误处理**: 使用 `try-catch` 捕获 `DbError` 异常 ## 与旧版对比 | 特性 | 旧版 SdkRdbHelper | 新版 GenericRdbHelper | |------|------------------|---------------------| | ArkTS兼容 | 部分兼容 | 完全兼容 | | 类型安全 | 使用Map | 使用强类型实体 | | 配置方式 | 外部配置 | 接口方法内定义 | | 自动建表 | 需手动SQL | 根据配置自动创建 |