首页 > 数据库 >Harmonyg环境使用ORM开发数据库应用入门教程

Harmonyg环境使用ORM开发数据库应用入门教程

时间:2024-10-27 19:45:17浏览次数:3  
标签:LOG suid 入门教程 LABEL Person ORM HiLog new Harmonyg

Harmony环境使用Bee入门向导

一、添加jar包

将bee相关的3个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);
        });
    }

标签:LOG,suid,入门教程,LABEL,Person,ORM,HiLog,new,Harmonyg
From: https://blog.csdn.net/abckingaa/article/details/143273544

相关文章

  • Transformer模型中的attention结构作用是什么
    Transformer模型中的attention结构是一种突出重要特征的机制,它使模型能够关注输入序列中的不同部分。Attention结构的主要作用包括:1、捕捉长距离依赖关系;2、并行计算;3、提供全局上下文信息。其中,捕捉长距离依赖关系意味着模型能够理解句子中相隔较远的词汇之间的联系,从而增强了对......
  • Pyside6 布局管理器(5)--- QFormLayout的使用
    一、QFormLayout的介绍(官翻)QFormLayout是一个方便的布局类,它以两列的形式布局其子元素。左列由标签组成,右列由“字段”小部件(行编辑器、数字显示框等)组成。 传统上,这种两栏布局是通过使用QGridLayout实现的。QFormLayout是一种更高级别的替代方案,具有以下优点:遵守不同平台......
  • transformer论文解读
    1.相关工作2.模型架构3.如何理解LayerNorm4.Encoder和Decoder结构5.从attention到ScaledDot-ProductAttention6.Multi-HeadAttention7.Transformer的三个multi-headattention的原理和作用8.Embedding和Softmax层9.PositionalEncoding10.为......
  • DYN / 消防局的设立 / Spread of Information / 将军令 题解
    前言四倍经验:[POI2011]DYN-Dynamite;[HNOI2003]消防局的设立;[ARC116E]SpreadofInformation;将军令。题意简述给你一棵\(n\)个结点的树和点集\(S\),你要选出\(k\)个关键点\(T\),求\(\min\max\limits_{u\inS}\min\limits_{v\inT}\operatorname{dis}(u,v)\)......
  • transformers 推理 Qwen2.5 等大模型技术细节详解(二)AutoModel 初始化和模型加载(免费
    接上文:transformers推理Qwen2.5等大模型技术细节详解(一)transformers包和对象加载老牛同学和大家通过Transformers框架的一行最常见代码fromtransformersimportAutoModelForCausalLM,走读了transformers包初始化代码的整个流程。从中体会到了dummy对象、LazyModule延迟......
  • 网络安全入门教程(非常详细)从零基础入门到精通,看完这一篇你就是网络安全高手了。
       关于我我算是“入行”不久的一个新人安全工作者,为什么是引号呢,因为我是个“半个野路子”出身。早在13年的时候,我在初中时期就已经在90sec、wooyun等社区一直学习、报告漏洞。后来由于升学的压力,我逐渐淡出了安全圈子,也没有继续学习技术。也因为这个原因,高考选择专业时......
  • Transformer 模型
            Transformer是一种基于自注意力机制的深度神经网络结构,由谷歌在2017年提出,最初应用于机器翻译任务。与传统的循环神经网络(RNN)不同,Transformer摒弃了序列依赖的结构,依靠自注意力机制全局建模输入序列中的依赖关系,极大提升了并行计算效率和捕捉长程依赖的能力......
  • 点跟踪论文—CoTracker: It is Better to Track Together使用Transform的时间与空间注
    CoTracker:ItisBettertoTrackTogether使用Transform的时间与空间注意力机制的密集点联合追踪算法详细解析文章概括总结:在之前学习的TrackingEverythingEverywhereAllatOnce(2023ICCV最佳学生论文)与RAFT:RecurrentAll-PairsFieldTransformsforOpticalF......
  • 点跟踪论文—RAFT: Recurrent All-Pairs Field Transforms for Optical Flow-递归的全
    点目标跟踪论文—RAFT:RecurrentAll-PairsFieldTransformsforOpticalFlow-递归的全对场光流变换读论文RAFT密集光流跟踪的笔记RAFT是一种新的光流深度网络结构,由于需要基于点去做目标的跟踪,因此也是阅读了像素级别跟踪的一篇ECCV2020的经典论文——RAFT,递归的......
  • np.random.multivariate_normal函数
    np.random.multivariate_normal是NumPy中生成多元正态分布随机样本的函数。它允许我们指定多个维度(变量)的均值和协方差矩阵,从而生成符合这些参数的随机样本。这个函数常用于模拟多维数据,特别是需要考虑变量间相关性的场景,比如机器学习中的数据生成。函数语法np.random.......