今天在适配家庭菜谱应用到 HarmonyOS NEXT 时,重点研究了 HarmonyOS Design 规范下的数据持久化方案。基于 API12 的 @ohos.data.relationalStore 关系型数据库模块,记录几个关键实现点:
1. 数据库建模遵循 HarmonyOS Design 的"简洁高效"原则,设计了三张核心表:
typescript
 // 数据库Schema定义  const SQL_CREATE_TABLE = `  CREATE TABLE IF NOT EXISTS recipe (      id INTEGER PRIMARY KEY AUTOINCREMENT,      name TEXT NOT NULL,      category TEXT CHECK(category IN ('中式','西式','日式')),      difficulty INTEGER DEFAULT 1  )  CREATE TABLE IF NOT EXISTS ingredient (      id INTEGER PRIMARY KEY,      recipe_id INTEGER,      name TEXT,      amount TEXT,      FOREIGN KEY (recipe_id) REFERENCES recipe(id) ON DELETE CASCADE  )`;  
       复制代码
 2. 数据库初始化
采用 HarmonyOS 推荐的异步事务处理:
typescript
 import relationalStore from '@ohos.data.relationalStore';  
let rdbStore: relationalStore.RdbStore;  const STORE_CONFIG = {      name: "RecipeDB.db",      securityLevel: relationalStore.SecurityLevel.S1  };  
async function initDB() {      try {          rdbStore = await relationalStore.getRdbStore(this.context, STORE_CONFIG);          await rdbStore.executeSql(SQL_CREATE_TABLE);          console.info('Database initialized');      } catch (err) {          console.error(`DB init failed: ${err.code}-${err.message}`);      }  }  
       复制代码
 3. 数据操作封装
为符合 HarmonyOS Design 的流畅体验要求,对 CRUD 操作做了线程优化:
typescript
 // 插入菜谱示例  async function insertRecipe(recipe: Recipe) {      const valueBucket = {          "name": recipe.name,          "category": recipe.category,          "difficulty": recipe.difficulty      };      try {          await rdbStore.insert("recipe", valueBucket);      } catch (err) {          console.error(`Insert failed: ${err.message}`);      }  }  
// 查询带食材的完整菜谱  async function getFullRecipe(recipeId: number) {      const predicates = new relationalStore.RdbPredicates("recipe");      predicates.equalTo("id", recipeId);      const recipe = await rdbStore.query(predicates, ["id","name"]);  
    const ingPredicates = new relationalStore.RdbPredicates("ingredient");      ingPredicates.equalTo("recipe_id", recipeId);      const ingredients = await rdbStore.query(ingPredicates);  
    return { ...recipe, ingredients };  }  
       复制代码
 遇到的问题:
· 跨设备同步场景下需要结合 DistributedDataKit 扩展
· 大数据量分页查询时需注意 Predicates 的 skip/limit 设置
明天计划尝试用 @ohos.data.preferences 实现用户偏好存储,与主数据库配合使用。整个开发过程深刻感受到 HarmonyOS Design 在数据一致性方面的严谨要求。
评论