Skip to content

快速上手

介绍

通过本章节你可以了解到 IBest-ORM 的安装方法和基本使用姿势。

一、安装

TIP

  • 如果想固定版本, 将 ^ 去掉即可
  • 如果想使用之前的某个版本, 请先使用以下命令安装 IBest-ORM, 然后在根目录下 oh-package.json5 中修改版本号

版本与 API 对应关系

组件库版本SDK 版本
v2.0.0 及以上api17 以上
v1.x.xapi17 以上
shell
ohpm install @ibestservices/ibest-orm

二、初始化

推荐方式:IBestORMInit(最简洁)

ts
import { IBestORMInit } from '@ibestservices/ibest-orm';

async onWindowStageCreate(windowStage: window.WindowStage): Promise<void> {
  // 一行代码初始化,默认开启 debug 日志,数据库文件名为 'ibest.db'
  await IBestORMInit(this.context);

  windowStage.loadContent('pages/Index');
}

自定义配置:

ts
await IBestORMInit(this.context, {
  name: 'myapp.db',    // 自定义数据库文件名
  debug: false         // 关闭调试日志
});

方式二:手动初始化(更多控制)

ts
import { initORM, createRelationalStoreAdapter } from '@ibestservices/ibest-orm';
import { relationalStore } from '@kit.ArkData';

async onWindowStageCreate(windowStage: window.WindowStage): Promise<void> {
  const adapter = await createRelationalStoreAdapter(this.context, {
    name: 'app.db',
    securityLevel: relationalStore.SecurityLevel.S1
  });

  initORM({
    adapter,
    logLevel: 'debug'
  });

  windowStage.loadContent('pages/Index');
}

三、定义模型

使用装饰器定义数据模型:

ts
import { Table, Column, PrimaryKey, CreatedAt, UpdatedAt, ColumnType } from '@ibestservices/ibest-orm';

@Table()  // 自动推断表名为 'user'
export class User {
  @PrimaryKey()  // 主键,默认自增
  id?: number;

  @Column()  // 自动推断类型
  name?: string;

  @Column({ type: ColumnType.INTEGER })
  age?: number;

  @CreatedAt()  // 自动记录创建时间
  createdAt?: string;

  @UpdatedAt()  // 自动记录更新时间
  updatedAt?: string;
}

四、基本使用

ts
import { getORM } from '@ibestservices/ibest-orm';

@Entry
@Component
export struct DemoPage {
  private orm = getORM();

  aboutToAppear(): void {
    // 1. 自动迁移表结构
    this.orm.migrate(User);

    // 2. 创建记录
    const user = new User();
    user.name = '张三';
    user.age = 18;
    this.orm.insert(user);

    // 3. 查询数据
    const users = this.orm.query(User)
      .where({ age: { gte: 18 } })
      .orderBy('createdAt', 'desc')
      .find();

    // 4. 更新数据
    user.age = 20;
    this.orm.save(user);

    // 5. 删除数据
    this.orm.deleteById(User, 1);
  }

  build() {
    // ...
  }
}

五、链式查询

IBest-ORM 提供了强大的链式查询 API:

ts
// 条件查询
const users = this.orm.query(User)
  .where({ name: '张三' })
  .where({ age: { gte: 18, lte: 30 } })
  .find();

// 复合条件
const results = this.orm.query(User)
  .where({ status: 'active' })
  .orWhere({ vipLevel: { gt: 3 } })
  .orderBy('createdAt', 'desc')
  .limit(10)
  .offset(0)
  .find();

// 选择字段
const names = this.orm.query(User)
  .select(['name', 'age'])
  .find();

// 聚合查询
const count = this.orm.query(User)
  .where({ age: { gte: 18 } })
  .count();

六、事务管理

ts
// 方式一:回调式事务(推荐)
this.orm.transaction(() => {
  this.orm.insert(user1);
  this.orm.insert(user2);
  // 自动提交,出错自动回滚
});

// 方式二:手动事务
this.orm.beginTransaction();
try {
  this.orm.insert(user1);
  this.orm.insert(user2);
  this.orm.commit();
} catch (e) {
  this.orm.rollback();
}

七、数据验证

ts
import { Required, Length, Range, Email, validate } from '@ibestservices/ibest-orm';

@Table()
export class User {
  @PrimaryKey()
  id?: number;

  @Required()
  @Length(2, 20)
  @Column()
  name?: string;

  @Range(0, 150)
  @Column()
  age?: number;

  @Email()
  @Column()
  email?: string;
}

// 验证数据
const user = new User();
user.name = 'A';  // 太短
user.age = 200;   // 超出范围

const result = validate(user);
if (!result.valid) {
  console.log('验证失败:', result.errors);
}

八、软删除

ts
import { SoftDelete } from '@ibestservices/ibest-orm';

@Table()
export class Article {
  @PrimaryKey()
  id?: number;

  @Column()
  title?: string;

  @SoftDelete()  // 软删除字段
  deletedAt?: string;
}

// 软删除(不会真正删除数据)
this.orm.query(Article).where({ id: 1 }).delete();

// 查询时自动过滤已删除记录
const articles = this.orm.query(Article).find();

// 包含已删除记录
const allArticles = this.orm.query(Article).withTrashed().find();

// 只查询已删除记录
const deletedArticles = this.orm.query(Article).onlyTrashed().find();

// 恢复已删除记录
this.orm.query(Article).where({ id: 1 }).restore();

下一步