当前位置:网站首页>HarmonyOS鸿蒙使用ORM Bee访问数据库实例
HarmonyOS鸿蒙使用ORM Bee访问数据库实例
2022-06-22 02:45:00 【abckingaa】
在使用HarmonyOS开发app应用时,经常会用到数据库存储数据。
要是用ORM框架,可以大大提高开发效率。
ORM Bee简单易用,文件小,性能好;同时支持Android和Harmony,还支持JDBC(可在JavaWeb等开发中使用)。
在Harmony和Android两个环境,可以用同一套Bee代码访问DB,提高代码重用,节省人力物。
以下说明,假设已创建了Data Ability工程。
工程全图如下:

一、添加jar包
将bee的jar包复制到entry包下的libs目录,右击jar包,
选择:Add as Libray... , 在跳出的对话框中选择ok.

完成后如下:

二、将相关配置注册到Bee
在启动的Ability ,添加相应的配置和注册信息。 若有自定义的配置在bee.properties则需要;则需要使用:BeeConfigInit.init();
将上下文注册到Bee;将创建表和更新表的回调类,注册到Bee;
以后就可以直接使用Bee了。
public class UserDataAbility extends Ability {
private static final String TAG = UserDataAbility.class.getSimpleName();
private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD000F00, TAG);
@Override
public void onStart(Intent intent) {
super.onStart(intent);
BeeConfigInit.init(); //若有自定义的配置在bee.properties则需要
ContextRegistry.register(this.getApplicationContext()); //将上下文注册到Bee
RdbOpenCallbackRegistry.register(new MyRdbOpenCallback()); //将创建表和更新表的回调类,注册到Bee
// BeeRdbStoreRegistry.register(rdbStore); //直接注册rdbStore对象也可以. 但需要自己去生成,配置信息也不好管理
}
}若有自定义的配置在bee.properties,将该文件放在entry\src\main\resources\rawfile目录下。如下图所示(整个代码结构,也可参考)。

三、定义安装app时,创建表和更新表的类
package ohos.samples.dataability;
import ohos.data.rdb.RdbOpenCallback;
import ohos.data.rdb.RdbStore;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.samples.dataability.bee.entity.*;
import ohos.samples.dataability.entity.Person;
import org.teasoft.honey.osql.autogen.Ddl;
import org.teasoft.honey.osql.core.HoneyContext;
public class MyRdbOpenCallback extends RdbOpenCallback {
private static final String TAG = "MyRdbOpenCallback";
private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD000F00, TAG);
@Override
public void onCreate(RdbStore store) {
try{
// store.executeSql( //手动写sql
// "create table if not exists " + "person (user_id integer primary key autoincrement, "
// + "name text not null, " + "age integer)");
HiLog.info(LABEL_LOG,"--------------------创建表.......开始.");
String sql= Ddl.toCreateTableSQL(new Person()); //不想写sql可以自动生成
HiLog.info(LABEL_LOG, "---------------create table sql:"+sql);
store.executeSql(sql);
store.executeSql(Ddl.toCreateTableSQL(new LeafAlloc()));
store.executeSql(Ddl.toCreateTableSQL(new Orders()));
store.executeSql(Ddl.toCreateTableSQL(new Tb_inaccount()));
store.executeSql(Ddl.toCreateTableSQL(new Tb_outaccount()));
store.executeSql(Ddl.toCreateTableSQL(new TestUser()));
} catch (Exception e) {
HiLog.error(LABEL_LOG, "---------------create table:"+e.getMessage());
}
HiLog.info(LABEL_LOG, "------------onCreate finished!");
}
@Override
public void onUpgrade(RdbStore store, int oldVersion, int newVersion) {
HoneyContext.setCurrentAppDB(store);
HiLog.info(LABEL_LOG,"--------------------更新表.......");
HiLog.info(LABEL_LOG, "%{public}s", "DataBase upgrade");
HoneyContext.removeCurrentAppDB();
}
}
四,可以在其它AbilitySlice中使用Bee操作数据库了
以下是select,update,insert,delete操作的例子。
主要语句如下:
Suid suid = BF.getSuid(); //简单的select,update,insert,delete操作
suid.insert(p);
suid.delete(new Person(), condition);
suid.update(p); //根据id修改对象
list = suid.select(new Person());//BF是BeeFactoryHelper的简称,也可以如下用法: //Suid suid=BeeFactoryHelper.getSuid();
详细代码如下:
private void insert(Component component) {
HiLog.info(LABEL_LOG, "----------------insert");
try {
Person p = new Person();
p.setName(getRandomName());
p.setAge(getRandomAge());
suid.insert(p);
HiLog.info(LABEL_LOG, "----------------insert结束.");
} catch (Exception e) {
HiLog.error(LABEL_LOG, "--------------insert--:" + e.getMessage());
}
query(true);
}
private void delete(Component component) {
HiLog.info(LABEL_LOG, "----------------delete");
try {
Condition condition = BF.getCondition();
condition.between("userId", 1, 2);
suid.delete(new Person(), condition);
} catch (Exception e) {
HiLog.error(LABEL_LOG, "--------------insert--:" + e.getMessage());
}
query(true);
}
private void update(Component component) {
HiLog.info(LABEL_LOG, "----------------update");
try {
Person p = new Person();
p.setName("Tom_update");
p.setAge(0);
p.setUserId(1);
suid.update(p); //根据id修改对象
} catch (Exception exception) {
HiLog.error(LABEL_LOG, "%{public}s", "update: dataRemote exception|illegalStateException");
}
query(true);
}
private void query(boolean queryAll) {
HiLog.info(LABEL_LOG, "----------------query");
getGlobalTaskDispatcher(TaskPriority.DEFAULT).asyncDispatch(() -> {
List<Person> list = null;
if (queryAll) { //查所有
list = suid.select(new Person());
}else {
list = suidRich.select(new Person(), 2, 5); //查从第2条开始的5条数据
}
appendText(list);
});
}边栏推荐
- Day13QMainWindow2021-09-28
- 【1. 快速排序】
- Day14QProgressBar2021-10-17
- Write the processing framework for playing
- 关于PMP考试,你想知道的知识都在这里了
- The brand, products and services are working together. What will Dongfeng Nissan do next?
- Markdown is proficient in Elementary Grammar and is compatible with marktext
- Neo4j 技能树正式发布,助你轻松掌握Neo4j图数据库
- EMC辐射发射整改-原理案例分析
- Li Kou today's question 1108 IP address invalidation
猜你喜欢

Li Kou today's question 1108 IP address invalidation

EMC Radiation Emission rectification - principle Case Analysis

【4. 高精度加法】

JVM makes wheels

Wechat applet film and television comment exchange platform system graduation design completion (6) opening defense ppt

C++ primer Chapter 2 summary of variables and basic types

Official release of ideal L9: retail price of 459800 yuan will be delivered before the end of August

Graphacademy course explanation: introduction to neo4j graph data science

自动化工具-监测文件的变化

Graphacademy course explanation: Fundamentals of neo4j graph data science
随机推荐
With the acceleration of industry wide digital transformation, what kind of storage will be more popular?
智翔金泰冲刺科创板:年营收3919万亏损超3亿 拟募资40亿
B-Tree
Deep Copy
GraphAcademy 课程讲解:《Neo4j 图数据科学简介》
What is a neural network
[9. submatrix sum]
June25,2022 PMP Exam clearance manual-5
【1. 快速排序】
[4. high precision addition]
Kubernetes code generator use
[2. merge sort]
并查集dsu
Architecture and practice of vivo container cluster monitoring system
Must the database primary key be self incremented? What scenarios do not suggest self augmentation?
JVM makes wheels
Wechat applet film and television review and exchange platform system graduation design completion (7) Interim inspection report
基于xposed框架hook使用
[1. quick sort]
How to select the appropriate version of neo4j (version 2022)