GreenDao基本功能的实现

greenDAO: Android ORM for your SQLite database

一.什么是GreenDao

Demo链接: https://github.com/liumaomao0209/GreenDaoDemo
GreenDAO是一个开源的AndroidORM,使SQLite数据库的开发再次变得有趣。它在节省开发时间的同时,减轻了开发人员对低级别数据库需求的处理。SQLite是一个令人敬畏的嵌入式关系数据库。尽管如此,编写SQL和解析查询结果仍然是非常繁琐和耗时的任务。GreenDAO通过将Java对象映射到数据库表(称为奥姆,“对象/关系映射”)。通过这种方式,您可以使用简单的面向对象API来存储、更新、删除和查询Java对象。

二.GreenDao的特点

GreenDAO的特点一目了然

  • 性能强大 (可能是Android最快的ORM)
  • 易用 有强大的API
  • 极小内存消耗
  • 体积小 GreenDAO小于100KB,所以对于应用程序APK的大小影响很小。
  • 数据库加密 支持SQLCiPHER,以确保用户数据的安全

当性能很重要时(数据访问频繁),GreenDao是一个很快的解决方案,它能够支持数千条记录的CRUD每秒,和OrmLite相比,GreenDAO要快几乎4.5倍。(准确数据请自行benchmark)。

greenDAO vs OrmLite

三.GreenDao的配置

1.导入插件
在project:build.gradle添加如下两行(位置已注释)


base.png
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    
    repositories {
        google()
        jcenter()
        mavenCentral() // 添加
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.2'
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // 添加
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

2.添加依赖和数据库配置
(1)在app:build.gradle添加library和plugin(位置已经注释为// apply plugin // add library)
(2)数据库配置信息,在android节点下


app.build.gradle
apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao' // apply plugin

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.maomao.technology.greendaodemo"
        minSdkVersion 27
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    greendao {
        schemaVersion 1 //数据库版本号,数据库升级使用
        daoPackage 'com.maomao.technology.greendaodemo.greendao' //代表GreenDao自动生成的有关数据库操作工具类所要存放的包名
        targetGenDir 'src/main/java' //路径
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'org.greenrobot:greendao:3.2.2' // add library
}

四.GreenDao的使用

首先大概看一下整体构建的样子:

base:数据库操作的基类
db:对用户表专门自定义的操作类.
greendao:建表时自动生成的类.

目录

1.创建一个用户类

Generated之下是build后自动生成的.
项目的build目录下或者自己设定的目录下还可以看到自动生成的三个类文件:
DaoMaster
DaoSession
UserDao

@Entity
public class UserBean {
    @Id(autoincrement = true)
    long id;
    @NotNull
    String name;
    String age;
    @Generated(hash = 47803367)
    public UserBean(long id, @NotNull String name, String age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }
    @Generated(hash = 1203313951)
    public UserBean() {
    }
    public long getId() {
        return this.id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getName() {
        return this.name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAge() {
        return this.age;
    }
    public void setAge(String age) {
        this.age = age;
    }
}
创建好后.png

注解说明:

@Id 注解选择 long / Long 属性作为实体ID。在数据库术语中,它是主键。参数自动增量,是使ID值不断增加(不会选用旧值)的标志。
@Property 让你定义一个非默认的列名,其属性映射到。如果不存在,greenDAO将在SQL杂交方式使用字段名(大写,下划线,而不是骆驼情况下,例如 customName将成为 CUSTOM_NAME)。注意:您目前只能使用内联常量来指定列名。
@Transient 表明这个字段不会被写入数据库,只是作为一个普通的java类字段,用来临时存储数据的,不会被持久化
@Entity 定义实体
@nameInDb 在数据库中的名字,如不写则为实体中类名
@indexes 索引
@schema 指定架构名称为实体
@active 无论是更新生成都刷新
@NotNull 不为null
@Unique 唯一约束
@ToMany 一对多
@OrderBy 排序
@ToOne 一对一
@Transient 不存储在数据库中
@generated 由greendao产生的构造函数或方法

2.构建两个管理DB的基类

1.BaseDBManager 所有的数据库操作类都继承自此
public class BaseDBManager {

    private AbstractDao mDao;

    public BaseDBManager(AbstractDao dao) {
        this.mDao = dao;
    }

    public void insert(T item) {
        mDao.insert(item);
    }

    public void insert(T... items) {
        mDao.insertInTx(items);
    }

    public void insert(List items) {
        mDao.insertInTx(items);
    }

    public void insertOrUpdate(T item) {
        mDao.insertOrReplace(item);
    }

    public void insertOrUpdate(T... items) {
        mDao.insertOrReplaceInTx(items);
    }

    public void insertOrUpdate(List items) {
        mDao.insertOrReplaceInTx(items);
    }

    public void deleteByKey(K key) {
        mDao.deleteByKey(key);
    }

    public void delete(T item) {
        mDao.delete(item);
    }

    public void delete(T... items) {
        mDao.deleteInTx(items);
    }

    public void delete(List items) {
        mDao.deleteInTx(items);
    }

    public void deleteAll() {
        mDao.deleteAll();
    }

    public void update(T item) {
        mDao.update(item);
    }

    public void update(T... items) {
        mDao.updateInTx(items);
    }

    public void update(List items) {
        mDao.updateInTx(items);
    }

    /**
     * 根据主键查询数据  如果没有涉及主键 则会报错
     *
     * @param key 主键
     * @return T
     */
    public T query(K key) {
        return mDao.load(key);
    }

    public List queryAll() {
        return mDao.loadAll();
    }

    public List query(String where, String... params) {
        return mDao.queryRaw(where, params);
    }

    public QueryBuilder getQueryBuilder() {
        return mDao.queryBuilder();
    }

    public long count() {
        return mDao.count();
    }

    public void refresh(T item) {
        mDao.refresh(item);
    }

    public void detach(T item) {
        mDao.detach(item);
    }

}


2.库名类
public interface DBConfig {
    String DB_NAME = "User.db";
}
3.编写USER库的操作类
操作类

三个类分别为

UserDBFactory 用户数据库工厂类 通过这个类统一下面两个类的功能,使用时调用这个类.
UserDBManage 数据库管理类,用于创建 删除 关闭数据库 获取session
UserInfoManage 用户信息管理类 对用户列表的增删改查放这里

public class UserDBFactory {
    private static UserDBFactory mInstance = null;
    private UserInfoManage userInfoManage;

    public static UserDBFactory getInstance() {
        if (mInstance == null) {
            synchronized (UserDBFactory.class) {
                if (mInstance == null) {
                    mInstance = new UserDBFactory();
                }
            }
        }
        return mInstance;
    }

    public UserInfoManage getUserInfoManage() {
        if (userInfoManage == null) {
            userInfoManage = new UserInfoManage(UserDBManage.getInstance(MyApplication.getApplication()).getDaoSession().getUserBeanDao());
        }
        return userInfoManage;
    }
}
public class UserDBManage {
    private static UserDBManage dbManage;
    private Context context;
    public static UserDBManage getInstance(Context context) {
        if (dbManage == null) {
            synchronized (UserDBManage.class) {
                if (dbManage == null) {
                    dbManage = new UserDBManage(context);
                }
            }
        }
        return dbManage;
    }
    private UserDBManage(Context context) {
        this.context = context;
    }
    private DaoMaster.DevOpenHelper mHelper;
    private DaoMaster mDaoMaster;
    private DaoSession mDaoSession;
    /**
     * 获取DaoSession * * @return
     */
    public synchronized DaoSession getDaoSession() {
        if (null == mDaoSession) {
            mDaoSession = getDaoMaster().newSession();
        }
        return mDaoSession;
    }
    /**
     * 关闭数据库
     */
    public synchronized void closeDataBase() {
        closeHelper();
        closeDaoSession();
    }
    /**
     * 判断数据库是否存在,如果不存在则创建 * * @return
     */
    private DaoMaster getDaoMaster() {
        if (null == mDaoMaster) {
            mHelper = new DaoMaster.DevOpenHelper(context, DBConfig.DB_NAME, null);
            mDaoMaster = new DaoMaster(mHelper.getWritableDb());
        }
        return mDaoMaster;
    }
    private void closeDaoSession() {
        if (null != mDaoSession) {
            mDaoSession.clear();
            mDaoSession = null;
        }
    }
    private void closeHelper() {
        if (mHelper != null) {
            mHelper.close();
            mHelper = null;
        }
    }
}

/**
 * Describe:DB操作类
 */

public class UserInfoManage extends BaseDBManager {
    public UserInfoManage(AbstractDao dao) {
        super(dao);
    }
}

五.增删改查功能实现

1.布局和代码目录展示


增删改查功能.png

布局和条目布局代码我就不写在这里了,各位自行定义.列表使用的是recyclerview;
2.自定义适配器

package com.maomao.technology.greendaodemo;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;

/**
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 * 创建日期:2019/4/19 on 15:45
 * 作   者:刘喵喵
 * 邮   箱:[email protected]
 * 描   述:
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 */
public class MyAdapter extends RecyclerView.Adapter {

    private final int mLayoutId;
    private final List mData;
    private final Context mContext;
    private final LayoutInflater inflater;

    public MyAdapter(List mData, int mLayoutId, Context mContext) {
        this.mData = mData;
        this.mLayoutId = mLayoutId;
        this.mContext = mContext;
        inflater = LayoutInflater.from(mContext);
    }


    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
        View view = inflater.inflate(mLayoutId, parent, false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
        MyViewHolder holder = (MyViewHolder) viewHolder;
        holder.key.setText(mData.get(i).getId()+"");
        holder.name.setText(mData.get(i).getName()+"");
        holder.age.setText(mData.get(i).getAge()+"");

    }

    @Override
    public int getItemCount() {
        return mData.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {

        private final TextView age;
        private final TextView name;
        private final TextView key;
        public MyViewHolder(View v) {
            super(v);
            name = v.findViewById(R.id.name);
            age = v.findViewById(R.id.age);
            key = v.findViewById(R.id.key);

        }


    }
}

3.主要功能逻辑

public class MainActivity extends Activity implements View.OnClickListener {

    private UserInfoManage userInfoManage;
    private List userBeanList = new ArrayList<>();
    private RecyclerView recyclerView;
    private MyAdapter myAdapter;
    private EditText keyEdit;
    private EditText valueEdit;
    private TextView add;
    private TextView delete;
    private TextView search;
    private TextView show;
    private TextView update;
    private UserBean userBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initview();
        initdata();
        UserDBFactory userDBFactory = new UserDBFactory();
        userInfoManage = userDBFactory.getUserInfoManage();
    }

    private void initdata() {
        myAdapter = new MyAdapter(userBeanList, R.layout.user_item, this);
        recyclerView.setAdapter(myAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
    }

    private void initview() {
        add = findViewById(R.id.add_btn);
        delete = findViewById(R.id.delete_btn);
        search = findViewById(R.id.search_btn);
        show = findViewById(R.id.show_btn);
        recyclerView = findViewById(R.id.recyclerView);
        keyEdit = findViewById(R.id.key_edt);
        valueEdit = findViewById(R.id.value_edt);
        update = findViewById(R.id.update_btn);
        add.setOnClickListener(this);
        delete.setOnClickListener(this);
        search.setOnClickListener(this);
        show.setOnClickListener(this);
        update.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Random mRandom = new Random();
        String key = keyEdit.getText().toString();
        switch (v.getId()) {
            case R.id.add_btn:
                //添加数据
                for (int i = 0; i < 10; i++) {
                    userBean = new UserBean();
                    userBean.setId(i + "");
                    int age = mRandom.nextInt(10) + 10;
                    userBean.setAge(age + "");
                    userBean.setName("瑶瑶" + i);
                    userInfoManage.insertOrUpdate(userBean);//插入或替换
                }
                myAdapter.notifyDataSetChanged();
                //显示
                show.performClick();
                break;
            case R.id.delete_btn:
                //删除key为..的数据
                userInfoManage.deleteByKey(key);
                show.performClick();
                break;
            case R.id.show_btn:
                userBeanList.clear();
                //查询所有并显示
                List userBeans = userInfoManage.queryAll();
                userBeanList.addAll(userBeans);
                myAdapter.notifyDataSetChanged();
                break;
            case R.id.search_btn:
                //搜索key为..的数据
                UserBean query = userInfoManage.query(key);
                if (query != null) {
                    userBeanList.clear();
                    userBeanList.add(query);
                    myAdapter.notifyDataSetChanged();
                } else {
                    Toast.makeText(this, "没有该条数据", Toast.LENGTH_SHORT).show();
                }
        break;
        case R.id.update_btn:
        //使用主键查询需要修改的数据
        UserBean userBean = userInfoManage.query(key);
        if (userBean != null) {
            userBean.setName(valueEdit.getText().toString());
            //修改
            userInfoManage.update(userBean);
            show.performClick();
        } else {
            Toast.makeText(this, "没有该条数据", Toast.LENGTH_SHORT).show();
        }
        break;
    }
}
}

4.全局context

public class MyApplication extends Application {

    //全局唯一的context
    private static MyApplication application;
    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        application = this;
    }
    public static Context getContext() {
        return application;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }
    /**
     * 获取全局唯一上下文
     *
     * @return BaseApplication
     */
    public static MyApplication getApplication() {
        return application;
    }
}

最后再放一次我的Demo链接

https://github.com/liumaomao0209/GreenDaoDemo
官方网站:http://greendao-orm.com/

你可能感兴趣的:(GreenDao基本功能的实现)