GenericRdbHelper - HarmonyOS 数据库ORM工具 (ArkTS版)
简介
GenericRdbHelper 是一个为 HarmonyOS 应用开发的轻量级 ORM 工具类,完全符合 ArkTS 规范,不使用 any 类型、装饰器等 TypeScript 特性。
主要特性
- ArkTS 兼容: 完全符合 ArkTS 编译器规范
- 接口驱动: 通过实现
IEntity接口定义表结构 - 类型安全: 使用明确的类型定义,无
any类型 - 完整的 CRUD: 支持增删改查、批量操作、条件查询等
- 自动建表: 根据 Model 配置自动创建数据库表
- 工厂模式: 使用工厂函数创建实体实例
安装
方式一:ohpm 安装(推荐)
ohpm install genericrdb
方式二:本地依赖
- 将
GenericRdb模块复制到你的项目目录中 - 在你的模块的
oh-package.json5文件中添加依赖:
{
"dependencies": {
"genericrdb": "file:../GenericRdb"
}
}
- 执行同步命令:
ohpm install
导入使用
安装完成后,在代码中导入所需的类:
import { GenericRdbHelper, IEntity, TableConfig, ColumnConfig, ColumnType, DbLog } from 'genericrdb';
核心文件
GenericRdb/src/main/ets/components/
├── decorators/
│ └── DbDecorators.ets # 元数据定义(TableConfig, ColumnConfig, IEntity)
├── GenericRdbHelper.ets # 通用数据库助手
├── SdkRdbHelper.ets # 旧版工具类
├── LocalSaveHelper.ts # 本地存储工具
├── PaySsUtils.ts # 支付工具类
└── DbLog.ts # 日志工具类
快速开始
1. 定义 Model 类
Model 类需要实现 IEntity 接口:
import { TableConfig, IEntity } from 'genericrdb';
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<string, string | number | null> {
const map = new Map<string, string | number | null>();
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<string, string | number | null>): void {
const idVal = map.get('id');
if (idVal !== null && idVal !== undefined) {
this.id = idVal as number;
}
// ... 其他字段类似
}
// 工厂方法
static createInstance(): UserInfo {
return new UserInfo();
}
}
2. 创建数据库助手
import { GenericRdbHelper } from 'genericrdb';
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 操作
// 插入
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() | 关闭数据库连接 |
注意事项
- 实现 IEntity 接口: Model 类必须实现
IEntity接口的三个方法 - 工厂方法: 必须提供静态工厂方法用于创建实例
- 类型转换: 查询结果需要手动转换为具体类型 (
entity as UserInfo) - 错误处理: 使用
try-catch捕获DbError异常
与旧版对比
| 特性 | 旧版 SdkRdbHelper | 新版 GenericRdbHelper |
|---|---|---|
| ArkTS兼容 | 部分兼容 | 完全兼容 |
| 类型安全 | 使用Map | 使用强类型实体 |
| 配置方式 | 外部配置 | 接口方法内定义 |
| 自动建表 | 需手动SQL | 根据配置自动创建 |