HarmonyOS NEXT 中级开发笔记:家庭菜谱应用的数据库设计与实践

48 阅读1分钟

今天在适配家庭菜谱应用到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在数据一致性方面的严谨要求。