同步操作将从 OpenHarmony-SIG/ohos_dataorm 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
dataORM是一个具有一行代码操作数据库或链式调用,备份、升级、缓存等特性的关系映射数据库
ohpm install @ohos/dataorm --save
OpenHarmony ohpm 环境配置等更多内容,请参考如何安装 OpenHarmony ohpm 包
import { Id } from '@ohos/dataorm';
import { NotNull } from '@ohos/dataorm';
import { Table, Columns } from '@ohos/dataorm';
import { Unique } from '@ohos/dataorm';
import { Index } from '@ohos/dataorm';
import { ToMany } from '@ohos/dataorm';
import { ColumnType } from '@ohos/dataorm';
import { ToOne } from '@ohos/dataorm';
@Table('NOTE')
export class Note {
@Id()
@Columns({ columnName: 'ID', types: ColumnType.num })
id: number;
@NotNull()
@Unique()
@Index(true)
@Columns({ columnName: 'TEXT', types: ColumnType.str })
text: string;
@Columns({ columnName: 'COMMENT', types: ColumnType.str })
comment: string;
@Columns({ columnName: 'DATE', types: ColumnType.str })
date: Date;
@Columns({ columnName: 'TYPE', types: ColumnType.str })
type: string;
@Columns({ columnName: 'MONEYS', types: ColumnType.real })
moneys: number;
//todo 类中必须在constructor中声明所有非静态变量,用于反射生成列
constructor(id?: number, text?: string, comment?: string, date?: Date, types?: string, moneys?: number) {
this.id = id;
this.text = text;
this.comment = comment;
this.date = date;
this.type = types;
this.moneys = moneys;
}
getMoneys(): number {
return this.moneys;
}
setMoneys(moneys: number) {
this.moneys = moneys;
}
getId(): number {
return this.id;
}
setId(id: number) {
this.id = id;
}
getText(): string {
return this.text;
}
/** Not-null value; ensure this value is available before it is saved to the database. */
setText(text: string) {
this.text = text;
}
getComment(): string {
return this.comment;
}
setComment(comment: string) {
this.comment = comment;
}
getDate(): Date {
return this.date;
}
setDate(date: Date) {
this.date = date;
}
getType(): string {
return this.type;
}
setType(types: string) {
this.type = types;
}
}
可使用注解使用示例及说明:
1、导入引用
import {Id} from '@ohos/dataorm';
2、使用方式:
A、
@Id()
id: number;
B、
@Id({ isPrimaryKey: true ,autoincrement:false})
id: number;
说明:在类属性中使用,定义表主键和键值是否是自增长。A和B的定义方式等同,isPrimaryKey值为true(是表主键),autoincrement值为false(不为自增长)
1、导入引用
import {Table} from '@ohos/dataorm';
2、使用方式:
@Table('NOTE')
export class Note {}
说明:在类头使用,定义表表名,如该示例定义为表名为NOTE。
1、导入引用
import {Columns} from '@ohos/dataorm';
2、使用方式:
@Columns({ columnName: 'ID', types: ColumnType.num })
text: string;
说明:在类属性中使用,定义在表中的列名和列类型。第一个参数为列名,第二个参数为列的数据类型
1、导入引用
import {NotNull} from '@ohos/dataorm';
2、使用方式:
A、
@NotNull()
text: string;
B、
@NotNull(true)
text: string;
说明:在类属性中使用,定义在表中该列是否可空,当为true值时,在表中该列值为非空值。其中A和B的定义方式等同,该列为非空值。
1、导入引用
import {Unique} from '@ohos/dataorm';
2、使用方式:
A、
@Unique()
text: string;
B、
@Unique(true)
text: string;
说明:在类属性中使用,定义在表中该列是否是唯一值,当为true值时,在表中该列值为唯一值。其中A和B的定义方式等同,该列为唯一值。
1、导入引用
import {Index} from '@ohos/dataorm';
2、使用方式:
A、
@Index()
text: string;
B、
@Index(true)
text: string;
c、
@Index(false)
text: string;
说明:在类属性中使用,定义创建索引表的列以及是否是唯一,当为true值时,为唯一。其中A定义为非唯一索引,B的定义为唯一索引,C定义为非唯一索引.A和C的定义等同。
1、导入引用
import { ToMany } from '@ohos/dataorm';
2、使用方式:
@ToMany({ targetClsName: "Student", joinProperty: [{ name: "ID", referencedName: "TID" }] })
@OrderBy("NAME ASC")
students: Array<Student>
说明:在类属性中使用,定义了目标关系表 targetClsName, 当前要查询的列 name 与外部目标表关联的列名 referencedName ,其中的name的值是目标referencedName的值 , 返回的是目标的表的对象数组。
调用时方式:
async queryByToManyFunctionTest() {
this.daoSession = globalThis.daoSession;
this.studentDao = this.daoSession.getBaseDao(Student);
var teacherId: string[] = ["1"]
let data = await this.studentDao.queryToManyListByColumnName("students", teacherId)
data.forEach(element => {
console.info("-----tonMany-----" + JSON.stringify(element))
});
}
说明: 获取目标表的Dao , 调用queryToManyListByColumnName(toManyColumnName: string, arr: string[]), 传入参数toManyColumnName为当前表所创建类的@ToMany下面的变量名,传入参数arr为关联列的查询值。
1、导入引用
import { JoinEntity } from '@ohos/dataorm';
2、使用方式
@JoinEntity({ entityName: 'JoinManyToDateEntity', targetClsName: 'DateEntity', sourceProperty: 'ID_TO_MANY', targetProperty: 'ID_DATE' })
@OrderBy("ID DESC")
dateEntityList: Array<DateEntity>
说明:在类属性中使用,定义了联接表之间的关系, entityName 为链接表的实体类名称, targetClsName 目标表的实体类, sourceProperty为连接实体中包含源(当前)实体id的属性的名称 ,targetProperty 为连接实体中包含目标实体id的属性的名称 , 返回的是目标的表的对象数组。
调用时方式:
async queryByJoinEntryFunctionTest(){
this.daoSession = globalThis.daoSession;
this.studentDao = this.daoSession.getBaseDao(DateEntity);
var teacherId: string[] = ["11"]
let data = await this.studentDao.queryToManyListByColumnName("dateEntityList", teacherId)
data.forEach(element => {
console.info("-----JoinEntry-----" + JSON.stringify(element))
});
}
说明: 获取目标表的Dao , 调用queryToManyListByColumnName(toManyColumnName: string, arr: string[]), 传入参数toManyColumnName为当前表所创建类的@ToMany下面的变量名,传入参数arr为关联列的查询值。
1、导入引用
import { ToOne } from '@ohos/dataorm';
2、使用方式
@ToOne({ value: 'TID', targetObj: Teacher })
teacher: Teacher
说明:在类属性中使用,定义了当前表 value为关联的列,targetObj 为关链创建的表的类。
调用时方式:
A、
async loadDeep() {
this.daoSession = globalThis.daoSession;
this.studentDao = this.daoSession.getBaseDao(Student);
let studentId = 1
let student: Student = await this.studentDao.loadDeep(studentId);
}
B、
async queryByToOneFunctionTest() {
this.daoSession = globalThis.daoSession;
this.studentDao = this.daoSession.getBaseDao(Student);
let columnName = this.studentDao.getPkProperty().columnName
let entityList = await this.studentDao.queryDeep("WHERE T." + columnName + "=?", ["1"]);
let entity3: Student = entityList[0];
}
说明: 获取目标表的Dao,拼接查询Sql 作为queryDeep(where: string, selectionArg: string[])的参数去查询。
globalThis.contt = this.context;
globalThis.entityCls = {}
let helper: ExampleOpeHelper = new ExampleOpenHelper(this.context, "notes.db");
let db: Database = await helper.getWritableDb();
helper.setEntities(Note);
helper.onCreate_D(db);
this.data.daoSession = new DaoMaster(db).newSession();
globalThis.contt = this.context;
globalThis.entityCls = {}
let helper: ExampleOpenHelper = new ExampleOpenHelper(context, "notes.db");
//设定数据加密密钥,加密后不可变更,加密和非加密库暂不能切换(普通数据库不能在设定为加密库,加密库不能变更为普通库,一经生成不可变更)
helper.setEncrypt(true);
let db: Database = await helper.getWritableDb();
//将所有的表 (新增,修改,已存在)加到全局
helper.setEntities(Note);
//调用创建表方法,将新增表创建,若无新增则不创建表
helper.onCreate_D(db);
this.data.daoSession = new DaoMaster(db).newSession();
private aboutToAppear() {
daoSess = globalThis.daoSession;
that.daoSession = daoSess;
noteDaos = that.daoSession.getBaseDao(Note);
}
/*
*监听
*/
private tabListener(): OnTableChangedListener<any>{
let that = this;
return {
async onTableChanged(t: any, err, action: TableAction) {
if (action == TableAction.INSERT) {
await that.updateNotes();
} else if(action == TableAction.UPDATE){
await that.updateNotes();
} else if(action == TableAction.DELETE){
await that.updateNotes();
} else if (action == TableAction.QUERY) {
}
}
}
}
/*
*添加监听
*/
noteDaos.addTableChangedListener(that.tabListener());
/**
* 移除监听
*/
noteDaos.removeTableChangedListener();
//新增
let date = new Date()
let comment = "Added on " + date.toLocaleString();
let note = new Note();
note.setText(this.noteText);
note.setComment(comment);
note.setDate(new Date());
note.setType(NoteType[NoteType.TEXT]);
noteDaos.insert(note);
//查询
let properties = globalThis.entityCls[Note.name];
let notesQuery = that.noteDao.queryBuilder().orderAsc(properties['text']).build();
this.arr = await this.notesQuery.list();
//删除
let properties = globalThis.entityCls[Note.name];
let deleteQuery = this.noteDao.queryBuilder().where(properties['text'].eq("bbb"))
.buildDelete();
deleteQuery.executeDeleteWithoutDetachingEntities()
接口准备
globalThis.contt = this.context;
//entity 属性集合,通过类名获取
globalThis.entityCls = {}
//记录要做处理的实体类,通过类名获取
globalThis.entityClsArr = {}
//全局临时变量,用于特殊情况存储数据
globalThis.entityClsRelationshipArr = {}
//entity 属性toMany、 toOne关系集合
globalThis.entityClsRelationship = {}
// regular SQLite database
let helper: ExampleOpenHelper = new ExampleOpenHelper(this.context, "notes.db");
//设定数据加密密钥,加密后不可变更,加密和非加密库暂不能切换(普通数据库不能在设定为加密库,加密库不能变更为普通库,一经生成不可变更)
helper.setEncrypt(true);
let db: Database = await helper.getWritableDb();
//将所有的表(新增,修改,已存在)加到全局
helper.setEntities(Note, Student, Teacher, JoinManyToDateEntity, DateEntity);
//调用创建表方法,将新增表创建,若无新增则不创建表
helper.onCreate_D(db);
noteDao.insert(note)
noteDao.update(note)
noteDao.delete(note)
noteDao.deleteByKey(id)
noteDao.queryBuilder().where(properties['text'].eq("bbb")).buildDelete()
noteDao.queryBuilder().list()
noteDao.queryBuilder.whereOr(properties['text'].eq("aaa"), properties['text'].eq("bbb"), properties['text'].eq("ccc")).list()
noteDao.load(id)
noteDao.refresh(note)
new qury().from(Note).query(Note).then((data) => { if(data)this.arr = data; })
qury().from(Note).eq("ID", 2).querySingle(Note).then((data) => {if(data) this.arr = data; })
noteDao.addTableChangedListener()
noteDao.removeTableChangedListener()
noteDao.save(note)
Migration.backupDB(dbName, tableName, version, context)
migration.execute(context)
executeSqlScript(resourceMgr: any, db: Database, rawFilename: string)
rawQuerys(sql: string, selectionArgs: Array<any>)
queryToManyListByColumnName(toManyColumnName: string, arr: string[])
queryToManyListByColumnName(toManyColumnName: string, arr: string[])
queryDeep(where: string, selectionArg: string[])
|---- dataORM
| |---- entry # 示例代码文件夹
| |---- dataORM # dataORM库文件夹
| |----annotation # 注解相关
| |----common # 公用类包
| |----database # 数据库相关
| |----dbflow # 链式查询
| |----base # 链式封装
| |----listener # 监听回调
| |----identityscope # 缓存相关
| |----internal # 内部调用文件
| |----query # 查询
| |---- index.ts # 对外接口
| |---- README.MD # 安装使用方法
使用过程中发现任何问题都可以提 Issue 给我们,当然,我们也非常欢迎你给我们发 PR 。
本项目基于 Apache License 2.0 ,请自由地享受和参与开源。
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。