zoukankan      html  css  js  c++  java
  • #2020征文手机#HarmonyOS对象关系映射数据库初体验

    上一篇体验了关系型数据库,那一部分API允许我们自由的手写SQL。

    这一篇的对象映射数据库是标准的ORM映射类似于Java中的hibernate框架,

    将对象映射为表,更改对象就是更改表。

    遇到问题

    1 在删除和更改时手动创建一个对象传递过去,无法删除或者更改。

    2 同一个对象多次添加会失败。

    这一个图放上边,因为把注解开关放到了项目的gradle文件中导致我以为这个API不能用

    实际上是放到模块的gradle文件中。

    #2020征文-手机#HarmonyOS对象关系映射数据库初体验

    这是一个数据库

    package com.datang.myapplication.slice;
    
    import ohos.data.orm.OrmDatabase;
    import ohos.data.orm.annotation.Database;
    import ohos.data.rdb.RdbOpenCallback;
    
    @Database(entities = {User.class}, version = 1)
    public class DB1 extends OrmDatabase {
    
        @Override
        public int getVersion() {
            return 0;
        }
    
        @Override
        public RdbOpenCallback getHelper() {
            return null;
        }
    }

    这是一个表

    package com.datang.myapplication.slice;
    
    import ohos.data.orm.OrmObject;
    import ohos.data.orm.annotation.Entity;
    import ohos.data.orm.annotation.PrimaryKey;
    
    @Entity(tableName = "user")
    public class User  extends OrmObject {
    
        // 此处将userId设为了自增的主键。注意只有在数据类型为包装类型时,自增主键才能生效。
        @PrimaryKey(autoGenerate = true)
        private Integer userId;
        private String name;
        private int age;
    
        public Integer getUserId() {
            return userId;
        }
    
        public void setUserId(Integer userId) {
            this.userId = userId;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        @Override
        public String toString() {
            return "User{" +
                    "userId=" + userId +
                    ", name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }

    CRUD基本操作

    package com.datang.myapplication.slice;
    
    import com.datang.myapplication.ResourceTable;
    import ohos.aafwk.ability.AbilitySlice;
    import ohos.aafwk.content.Intent;
    import ohos.agp.components.Button;
    import ohos.data.DatabaseHelper;
    import ohos.data.orm.AllChangeToTarget;
    import ohos.data.orm.OrmContext;
    import ohos.data.orm.OrmObjectObserver;
    import ohos.data.orm.OrmPredicates;
    import ohos.data.rdb.*;
    import ohos.data.resultset.ResultSet;
    import ohos.hiviewdfx.HiLog;
    import ohos.hiviewdfx.HiLogLabel;
    
    import java.util.List;
    
    //关系型数据库
    public class MainAbilitySlice2 extends AbilitySlice {
    
        HiLogLabel label = new HiLogLabel(HiLog.LOG_APP, 0x00201, "MY_TAG");
        OrmContext context = null;
    
        @Override
        public void onStart(Intent intent) {
            super.onStart(intent);
            super.setUIContent(ResourceTable.Layout_ability_main2);
            initDB();
    
            insert();
            select();
            delete();
            update();
    
            //注册 user 表监听事件 insert update delete 会触发
            context.registerEntityObserver("user", (o, a) -> {
                HiLog.info(label, "触发回调了》》》》》》》》》》》》》》》》》》");
            });
        }
    
    
        @Override
        public void onActive() {
            super.onActive();
        }
    
        public void initDB() {
            DatabaseHelper helper = new DatabaseHelper(this);
            context = helper.getOrmContext("DB1", "DB1.db", DB1.class);
        }
    
        //增加
        public void insert() {
            Button button = (Button) findComponentById(ResourceTable.Id_add);
            button.setClickedListener(e -> {
    
                for (int i = 1; i <= 10; i++) {
                    //将这个对象添加进去,此外这里如果将User对象放到循环外,则会添加失败抛出异常
                    //意味着不能对同一个对象做多次添加。就算属性都一样,也要创建多个。不知道是不是
                    //bug
                    User user = new User();
                    user.setName("Zhang" + i);
                    user.setAge(i);
                    boolean isSuccessed = context.insert(user);
                    //没有刷新添加不进去
                    isSuccessed = context.flush();
                    HiLog.info(label, "添加是否成功%{public}d,%{public}s", i, isSuccessed);
                }
            });
    
    
        }
    
        //查询
        public void select() {
            Button button2 = (Button) findComponentById(ResourceTable.Id_get);
            button2.setClickedListener(e -> {
                OrmPredicates query = context.where(User.class);
                List<User> users = context.query(query);
                users.forEach(c -> {
                    HiLog.info(label, "查询结果%{public}s", users);
                });
            });
        }
    
        //删除
        public void delete() {
            Button button3 = (Button) findComponentById(ResourceTable.Id_del);
            button3.setClickedListener(e -> {
                // 删除数据 User{userId=1, name='Zhang1', age=1}
                //直接创建一个 user对象,属性全部设置也不会删除
    //            User user = new User();
    //            user.setUserId(1);
    //            user.setName("Zhang1");
    //            user.setAge(1);
    
                //User{userId=1, name='Zhang1', age=1}
                //从数据库查出来的却可以用,实际上和上边那个创建出来的属性一样
                OrmPredicates predicates = context.where(User.class);
                predicates.equalTo("userId", 1);
                List<User> users = context.query(predicates);
                User user = users.get(0);
    
                boolean delete = context.delete(user);
                //需要flush
                boolean flush = context.flush();
                HiLog.info(label, "是否删除%{public}s", flush);
    
    
                //这种删除方式就类似批量删除了,只给出删除条件,多少都删
                OrmPredicates predicates2 = context.where(User.class);
                predicates2.equalTo("name", "Zhang2");
                int delete2 = context.delete(predicates2);
                //并且不用flush
                //boolean flush = context.flush();
                HiLog.info(label, "是否删除%{public}d", delete2);
            });
        }
    
    
        //更改
        public void update() {
            Button button4 = (Button) findComponentById(ResourceTable.Id_upd);
            button4.setClickedListener(e -> {
                //同样手动创建的user也无法更改
    //            User user = new User();
    //            user.setUserId(1);
    //            user.setName("李四特");
    //            user.setAge(33);
    
                //查询出来
                OrmPredicates predicates = context.where(User.class);
                predicates.equalTo("userId", 1);
                List<User> users = context.query(predicates);
                User user = users.get(0);
                user.setName("李四特");
                //更改
                boolean update = context.update(user);
                //需要flush
                boolean flush = context.flush();
                HiLog.info(label, "更改成功:%{public}s", update);
    
                //这种方式也是批量更改,更改后的值在 ValuesBucket中存储
                OrmPredicates predicates2 = context.where(User.class);
                predicates2.equalTo("userId", 2);
                ValuesBucket valuesBucket = new ValuesBucket();
                valuesBucket.putInteger("age", 31);
                valuesBucket.putString("name", "王二麻子");
                context.update(predicates2, valuesBucket);
                //不需要flush
                //boolean flush = context.flush();
                HiLog.info(label, "更改成功:%{public}s", update);
            });
        }
    
    }

    作者:顶风少年

    想了解更多内容,请访问: 51CTO和华为官方战略合作共建的鸿蒙技术社区https://harmonyos.51cto.com/

  • 相关阅读:
    java 基本数据类型
    public 类、default 类、内部类、匿名内部类
    使用jar命令打jar/war包、创建可执行jar包、运行jar包、及批处理脚本编写
    jdk下载及安装
    数据库常用查询
    数据库锁的几种类型
    ORACLE表批量迁移表空间
    如何区分Oracle的数据库,实例,服务名,SID
    ORACLE下如何获得全部的索引创建语句
    oracle 内存分配和调优 总结
  • 原文地址:https://www.cnblogs.com/HarmonyOS/p/14245187.html
Copyright © 2011-2022 走看看