鸿蒙开发之数据库查询ORM 实践
·
在鸿蒙(HarmonyOS)应用开发中,实现ORM(对象关系映射)可以显著简化数据库操作,提升开发效率和代码可维护性。下面我将介绍如何在鸿蒙中实现ORM风格的数据库查询。
一、ORM基础概念
ORM(Object-Relational Mapping)是一种将数据库表映射为编程语言中的对象的技术,主要优势包括:
-
避免直接编写SQL语句
-
以面向对象的方式操作数据
-
自动处理对象与数据库表之间的转换
二、鸿蒙ORM实现方案
- 基础ORM框架设计
// database/orm/BaseEntity.ets
export abstract class BaseEntity {
// 标记为抽象方法,子类必须实现
abstract getTableName(): string;
// 获取主键列名
getPrimaryKey(): string {
return 'id';
}
// 转换为ValuesBucket
toValuesBucket(): rdb.ValuesBucket {
const values = new rdb.ValuesBucket();
const properties = Object.getOwnPropertyNames(this.constructor.prototype)
.filter(prop => prop !== 'constructor' && prop !== 'getTableName' && prop !== 'getPrimaryKey');
properties.forEach(prop => {
const value = this[prop];
if (value !== undefined) {
const type = typeof value;
if (type === 'string') {
values.putString(prop, value);
} else if (type === 'number') {
values.putInteger(prop, value);
}
// 可扩展其他类型处理
}
});
return values;
}
}
- ORM查询构建器
// database/orm/QueryBuilder.ets
export class QueryBuilder<T extends BaseEntity> {
private predicates: rdb.RdbPredicates;
private table: string;
constructor(table: string) {
this.table = table;
this.predicates = new rdb.RdbPredicates(table);
}
// 条件查询
where(column: string, operator: string, value: any): QueryBuilder<T> {
this.predicates.equalTo(column, value);
return this;
}
// 排序
orderBy(column: string, isAsc: boolean): QueryBuilder<T> {
this.predicates.orderByAsc(column);
if (!isAsc) {
this.predicates.orderByDesc(column);
}
return this;
}
// 限制查询数量
limit(count: number): QueryBuilder<T> {
this.predicates.setLimit(count);
return this;
}
// 执行查询
async execute(store: rdb.RdbStore): Promise<T[]> {
const resultSet = await store.query(this.predicates);
const entities: T[] = [];
while (await resultSet.goToNextRow()) {
const entity = new (this.constructor as any)() as T;
const columns = await resultSet.getColumnNames();
columns.forEach(column => {
const type = resultSet.getColumnType(column);
switch (type) {
case rdb.ColumnType.TYPE_INTEGER:
entity[column] = resultSet.getInteger(column);
break;
case rdb.ColumnType.TYPE_STRING:
entity[column] = resultSet.getString(column);
break;
// 其他类型处理...
}
});
entities.push(entity);
}
await resultSet.close();
return entities;
}
}
3.示例
// entities/User.ets
import { BaseEntity } from '../database/orm/BaseEntity';
export class User extends BaseEntity {
id?: number;
name: string;
age: number;
getTableName(): string {
return 'User';
}
}
- Repository实现
// repositories/UserRepository.ets
import { BaseRepository } from './BaseRepository';
import { User } from '../entities/User';
export class UserRepository extends BaseRepository<User> {
constructor() {
super(new User());
}
async findByName(name: string): Promise<User[]> {
return new QueryBuilder<User>('User')
.where('name', '=', name)
.orderBy('name', true)
.limit(10)
.execute(this.store);
}
}
三、高级ORM功能实现
- 关联查询处理
// 简单的一对一关联查询
async getUserWithProfile(userId: number): Promise<{user: User, profile: Profile}> {
const userQuery = new QueryBuilder<User>('User')
.where('id', '=', userId)
.execute(this.store);
const profileQuery = new QueryBuilder<Profile>('Profile')
.where('user_id', '=', userId)
.execute(this.store);
const [users, profiles] = await Promise.all([userQuery, profileQuery]);
return {
user: users[0],
profile: profiles[0]
};
}
- 事务支持
async saveUserWithTransaction(user: User, profile: Profile): Promise<void> {
await this.executeTransaction(async (store) => {
const userRepo = new UserRepository();
userRepo.setStore(store);
const profileRepo = new ProfileRepository();
profileRepo.setStore(store);
const userId = await userRepo.insert(user);
profile.userId = userId;
await profileRepo.insert(profile);
});
}
- 查询缓存
private queryCache: Map<string, any[]> = new Map();
async cachedQuery(key: string, query: () => Promise<any[]>): Promise<any[]> {
if (this.queryCache.has(key)) {
return this.queryCache.get(key)!;
}
const result = await query();
this.queryCache.set(key, result);
return result;
}
四、示例
// 使用ORM进行数据库操作
const userRepository = new UserRepository();
// 插入数据
const newUser = new User();
newUser.name = '张三';
newUser.age = 28;
await userRepository.insert(newUser);
// 查询数据
const users = await userRepository.findByName('张三');
console.log(users.map(u => u.toJSON()));
// 更新数据
const userToUpdate = users[0];
userToUpdate.age = 29;
await userRepository.update(userToUpdate);
// 删除数据
await userRepository.delete(userToUpdate.id!);
注意事项
-
类型安全:确保TypeScript类型与数据库列类型匹配
-
内存管理:及时关闭ResultSet释放资源
-
并发控制:多线程环境下注意数据一致性
-
错误处理:统一处理数据库操作异常
通过以上实现,可以在鸿蒙应用中构建一个功能完善、使用便捷的ORM框架,显著提升数据库操作的开发效率和代码质量。
更多推荐


所有评论(0)