HarmonyOS 对象数据库

1.配置

2.使用

一 配置

参考配置:

HarmonyOS 基础数据库 - biind - 博客园 (cnblogs.com)

跟基础数据库配置一样

二 使用

1.新建entiry类,继承OrmObject

2.新建store类,继承OrmDatabase

3.新增、更新、删除、查询单条,查询集合

package com.example.demo2.db;

import com.example.demo2.entity.User;
import ohos.data.orm.OrmDatabase;
import ohos.data.orm.annotation.Database;
import ohos.data.rdb.RdbOpenCallback;

@Database(entities = {User.class}, version = 1)
public class UserStore extends OrmDatabase {

    @Override
    public int getVersion() {
        return 0;
    }

    @Override
    public RdbOpenCallback getHelper() {
        return null;
    }
}
package com.example.demo2.entity;

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 {

    @PrimaryKey(autoGenerate = true)
    private int id;
    private String name;
    private int age;
    private double salary;

    public User() {
    }

    public User(int id, String name, int age, double salary) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    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;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", salary=" + salary +
                '}';
    }
}
package com.example.demo2.db;

import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.data.orm.OrmContext;
import ohos.data.orm.OrmMigration;
import ohos.data.rdb.RdbOpenCallback;
import ohos.data.rdb.RdbStore;
import ohos.data.rdb.StoreConfig;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

public class DBConfig {
    private final HiLogLabel HI_LOG_LABEL = new HiLogLabel(HiLog.LOG_APP, 1, "DBConfig");

    private String data_base_name = "mydb.db";
    private String data_base_name_alias = "mydb";

    private DatabaseHelper databaseHelper;
    private OrmContext ormContext;

    private StoreConfig config;
    private RdbStore rdbStore;

    public DBConfig(Context context) {
        databaseHelper = new DatabaseHelper(context);
    }

    public OrmContext getConnectionContext(Class store) {
        this.ormContext = databaseHelper.getOrmContext(data_base_name_alias, data_base_name, store, new OrmMigration[0]);
        return this.ormContext;
    }

    public RdbStore getConnectionWithSql(String sql) {
        config = StoreConfig.newDefaultConfig(data_base_name);

        rdbStore = databaseHelper.getRdbStore(config, 1, new RdbOpenCallback() {
            @Override
            public void onCreate(RdbStore rdbStore) {
                rdbStore.executeSql(sql);
            }

            @Override
            public void onUpgrade(RdbStore rdbStore, int i, int i1) {

            }
package com.example.demo2.utils;

import com.example.demo2.data.Student;
import com.example.demo2.db.DBConfig;
import com.example.demo2.db.UserStore;
import com.example.demo2.entity.User;
import ohos.app.Context;
import ohos.data.orm.OrmContext;
import ohos.data.orm.OrmPredicates;
import ohos.data.rdb.ValuesBucket;
import ohos.data.resultset.ResultSet;

import java.util.ArrayList;
import java.util.List;

public class UserUtils {
    private OrmContext orm;
    private DBConfig config;

    public UserUtils(Context context) {
        config = new DBConfig(context);
        orm = config.getConnectionContext(UserStore.class);
    }

    public boolean insert(User user) {
        boolean insert = orm.insert(user);
        return orm.flush();
    }

    public boolean delete(int id) {
        OrmPredicates predicates = orm.where(User.class).equalTo("id", id);
        int i = orm.delete(predicates);

        return i > 0 ? true : false;
    }

    public boolean update(int id, User user) {
        OrmPredicates predicates = orm.where(User.class).equalTo("id", id);
        ValuesBucket bucket = new ValuesBucket();
        bucket.putInteger("id", user.getId());
        bucket.putString("name", user.getName());
        bucket.putInteger("age", user.getAge());
        bucket.putDouble("salary", user.getSalary());
        int i = orm.update(predicates, bucket);
        return i > 0 ? true : false;
    }

    public List<User> queryList(String name) {
        List<User> list = new ArrayList<User>();
        OrmPredicates predicates = orm.where(User.class).like("name", name);
        ResultSet query = orm.query(predicates, new String[]{"id", "name", "age", "salary"});
        while (query.goToNextRow()) {
            User user = new User();
            user.setId(query.getInt(query.getColumnIndexForName("id")));
            user.setName(query.getString(query.getColumnIndexForName("name")));
            user.setAge(query.getInt(query.getColumnIndexForName("age")));
            user.setSalary(query.getDouble(query.getColumnIndexForName("salary")));
            list.add(user);
        }

        return list;
    }
}

 


        });

        return rdbStore;
    }
}
package com.example.demo2.slice;

import com.example.demo2.ResourceTable;
import com.example.demo2.data.Student;
import com.example.demo2.entity.User;
import com.example.demo2.utils.StudentUtils;
import com.example.demo2.utils.UserUtils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.util.List;

public class UserDBTestSlice extends AbilitySlice {
    private final HiLogLabel hiLogLabel = new HiLogLabel(HiLog.LOG_APP, 1, "UserDBTestSlice");

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_db_test);

        Button add = (Button) findComponentById(ResourceTable.Id_btnAdd);
        Button update = (Button) findComponentById(ResourceTable.Id_btnUpdate);
        Button delete = (Button) findComponentById(ResourceTable.Id_btnDelete);
        Button one = (Button) findComponentById(ResourceTable.Id_btnQueryById);
        Button list = (Button) findComponentById(ResourceTable.Id_btnQueryAll);
        add.setClickedListener(this::onClick);
        update.setClickedListener(this::onClick);
        delete.setClickedListener(this::onClick);
        one.setClickedListener(this::onClick);
        list.setClickedListener(this::onClick);
    }

    private void onClick(Component component) {
        if (component.getId() == ResourceTable.Id_btnAdd) {
            try {
                for (int i = 0; i < 10; i++) {
                    User user = new User(i, "jack", 30 + i, 12000);

                    boolean b = new UserUtils(UserDBTestSlice.this).insert(user);
                    if (b) {
                        HiLog.info(hiLogLabel, "---插入成功-----" + i);
                    }
                }

            } catch (Exception e) {
                HiLog.info(hiLogLabel, "---插入失败-----" + e.getMessage());
            }
        }

        if (component.getId() == ResourceTable.Id_btnQueryAll) {
            try {
                List<User> list = new UserUtils(UserDBTestSlice.this).queryList("jack");
                HiLog.info(hiLogLabel, "---查询全部:size-----" + list.size());
                for (int i = 0; i < list.size(); i++) {
                    HiLog.info(hiLogLabel, list.get(i).toString());
                }
                HiLog.info(hiLogLabel, "---查询全部成功-----");

            } catch (Exception e) {
                HiLog.info(hiLogLabel, "---查询全部失败-----" + e.getMessage());
            }
        }
    }

    @Override
    protected void onActive() {
        super.onActive();
    }

    @Override
    protected void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_parent"
    ohos:width="match_parent"
    ohos:alignment="center"
    ohos:orientation="vertical">

    <Button
        ohos:id="$+id:btnAdd"
        ohos:height="50vp"
        ohos:width="200vp"
        ohos:background_element="$graphic:background_button"
        ohos:text="新增1条数据"
        ohos:text_color="#FFFFFF"
        ohos:text_size="20fp"
        ohos:top_margin="20vp">
    </Button>

    <Button
        ohos:id="$+id:btnDelete"
        ohos:height="50vp"
        ohos:width="200vp"
        ohos:background_element="$graphic:background_button"
        ohos:text="删除1条数据"
        ohos:text_color="#FFFFFF"
        ohos:text_size="20fp"
        ohos:top_margin="20vp">
    </Button>

    <Button
        ohos:id="$+id:btnUpdate"
        ohos:height="50vp"
        ohos:width="200vp"
        ohos:background_element="$graphic:background_button"
        ohos:text="更新1条数据"
        ohos:text_color="#FFFFFF"
        ohos:text_size="20fp"
        ohos:top_margin="20vp">
    </Button>

    <Button
        ohos:id="$+id:btnQueryById"
        ohos:height="50vp"
        ohos:width="200vp"
        ohos:background_element="$graphic:background_button"
        ohos:text="查询1条数据"
        ohos:text_color="#FFFFFF"
        ohos:text_size="20fp"
        ohos:top_margin="20vp">
    </Button>

    <Button
        ohos:id="$+id:btnQueryAll"
        ohos:height="50vp"
        ohos:width="200vp"
        ohos:background_element="$graphic:background_button"
        ohos:text="查询全部数据"
        ohos:text_color="#FFFFFF"
        ohos:text_size="20fp"
        ohos:top_margin="20vp">
    </Button>
</DirectionalLayout>

 

 

 

 

 

posted on 2021-12-05 08:48  biind  阅读(123)  评论(0编辑  收藏  举报