# mtrdb_demo **Repository Path**: geno/mtrdb_demo ## Basic Information - **Project Name**: mtrdb_demo - **Description**: mtrdb 使用 demo - **Primary Language**: Unknown - **License**: Apache-2.0 - **Default Branch**: main - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 1 - **Created**: 2024-12-15 - **Last Updated**: 2025-05-21 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # MTRdb-的使用demo 包地址:[openharmony mtrdb](https://ohpm.openharmony.cn/#/cn/detail/mtrdb) 包含增删改查、数据库升级;OR映射的对象在多线程间共享使用的事例。 项目需要自己配置签名。 ## 基本使用方式 * 下载 `ohpm install @mtxx/mtrdb` * 初始化 ```typescript //初始化数据库 MTRdb.init({ application: this.context.getApplicationContext(), //applicationcontext rdbConfig: { name: 'DEMO_DB',//数据库名 securityLevel: relationalStore.SecurityLevel.S1 }, dbVersion: 1, //数据库版本 enableLog: true, //是否开启log logLevel: hilog.LogLevel.INFO //log 输出等级 }) ``` * 实现表接口类`BaseTableInterface` ```typescript export class XXTableConfig implements BaseTableInterface { /** * 表名 */ tableName = `TABLE_NAME` /** * 表创建语句 */ sqlCreate: string = `CREATE TABLE IF NOT EXISTS ……` /** * 最新的表列名 */ columnNames: string[] = [`id`, `tab`] /** * 表主键,支持多主键 */ uniqueColumnName: string[] = ['id', 'tab'] ``` * 继承BaseTableDao `BaseTableDao` ```typescript export class XXBeanDao extends BaseTableDao { saveParamsToString(model: XXBean): void { //高级用法,复杂嵌套对象,只需要数据时,可以直接 string 化; //以 string 形式,保存的的对象,一般直接JSON.stringify } getParamsFromString(model: XXBean): void { //从 string 还原 数据,填充到 model } generateModelObj(): XXBean { return new XXBean() } } ``` * 实现BaseModel `BaseModel`,支持Sendable * model 的属性 需要 和 表的列名一致,否则会映射错误 getUniqueProp(): Map//返回表的主键值 * getDbIgnoreObjProp(): string[]//返回需要忽略的二级对象的属性名 ```typescript @Sendable export class XXBean implements BaseModel { id: number = 0; tab: string = ''; constructor(id:number,tab:string){ this.id = id this.tab = tab } getUniqueProp(): Map { return new Map([['id', this.id], ['tab', this.tab]]) } getDbIgnoreObjProp(): string[] { return ['ignore_prop'] } ``` * 初始化Dao对象,建议做缓存 ```typescript export class DemoDB { private static dao: XXBeanDao public static async getXXDao(): Promise { return new Promise((resolve) => { if (DemoDB.dao) { resolve(DemoDB.dao) return } DemoDB.dao = new XXBeanDao(new XXTableConfig(), () => { resolve(DemoDB.dao) }) }) } } ``` * new Dao()时,就会自动初始化对应的数据表;之后通过 Dao 进行数据对象的操作即可。 ```typescript DemoDB.getXXDao().then((dao) => { dao.insert(new XXBean()).then((result)=>{ //todo }) }) ``` * 数据库升级 MTRdb init时,config 增加版本号 ```typescript //初始化数据库 MTRdb.init({ application: this.context.getApplicationContext(), //applicationcontext rdbConfig: { name: 'DEMO_DB',//数据库名 securityLevel: relationalStore.SecurityLevel.S1 }, dbVersion: 2, //数据库+1 enableLog: true, //是否开启log logLevel: hilog.LogLevel.INFO //log 输出等级 }) ``` TableInterface实现类增加升级配置updateConfig ```typescript export class XXTableConfig implements BaseTableInterface { updateConfig: MaterialUpConfig = new MaterialUpConfig(this.tableName) } ``` 配置升级内容 ```typescript export class MaterialUpConfig extends BaseUpConfig { get allVersionInfo(): Map { return this.allMap; } addList: MTRdbColumn = new Map([ ["test", ColumnType.TEXT] ]) version2: MTRdbMigrationInfo = { table: this.tableName, addList: this.addList } /** * 针对key,需要跟数据库DB的版本做对应 */ allMap: Map = new Map([ [2, this.version2] ]) } ``` 如果有改变字段的操作,需要同步修改 tableInterface 的 sqlcreate 和 columns 相对应的信息; 如果只是新增字段,并且使用了`updateConfig.allNewColumnCreate()`和`this.updateConfig.allNewColumnList()`;如下,则可以不用处理。 updateconfig 会自动把所有新增字段添加上。 ```typescript sqlCreate: string = `CREATE TABLE IF NOT EXISTS ${this.tableName} ( material_id INTEGER, tab_id TEXT DEFAULT (''), extra_info_is_with_filter INTEGER, ${this.updateConfig.allNewColumnCreate(",")} PRIMARY KEY (material_id,tab_id) )` columnNames: string[] = [`material_id`, `tab_id`, `extra_info_is_with_filter`, ...this.updateConfig.allNewColumnList()] ``` 做完以上操作后,再下一次init之后,获取 rdbStore 的时候,就会自动完成数据库升级。