GreenDao 的簡介和使用

greenDAO簡介

greenDAO是一款開源的面向 Android 的輕便、快捷的 ORM 框架,將 Java 對象映射到SQLite數據庫中,我們操作數據庫的時候,不再需要編寫複雜的 SQL語句, 在性能方面,greenDAO針對 Android 進行了高度優化, 最小的內存開銷 、依賴體積小 同時還是支持數據庫加密。

ORM 框架有很多,比較著名的有 OrmLite , ActiveAndroid 等

greenDAO項目地址:https://github.com/greenrobot/greenDAO

視頻講解鏈接
https://www.bilibili.com/video/BV1Qt4y117Up

greenDAO集成

第一步 在項目的build.gradle 文件中配置classpath

buildscript {
    apply from: 'script.gradle', to: buildscript
    repositories {
        jcenter()
        maven {url 'https://maven.google.com'}
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.1'
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

第二步 在app的build.gradle 文件中引入greenDao插件

apply plugin: 'org.greenrobot.greendao'

第三步 在app的build.gradle 文件中導入greenDao依賴包

implementation 'org.greenrobot:greendao-generator:3.2.2'

第四步 在app的build.gradle 文件中配置數據庫相關信息

android {
    compileSdkVersion 28
    buildToolsVersion '28.0.3'
    aaptOptions.cruncherEnabled = false
    aaptOptions.useNewCruncher = false

    greendao {
        schemaVersion 1//數據庫版本號
        daoPackage 'cn.***.greendao'//設置DaoMaster、DaoSession、Dao包名
        targetGenDir 'src/main/java'//設置DaoMaster、DaoSession、Dao目錄
        //targetGenDirTest:設置生成單元測試目錄
        //generateTests:設置自動生成單元測試用例
    }
 }

這樣greenDao就集成好了,下面我們就看怎麼使用greenDao.

greenDao的使用

1,新建實體類
新建一個實體類,對整個實體類使用註解 @Entity

@Entity public class Student { }

接下來添加類的屬性

@Entity
public class Student {
    @Id //@id 是設置主鍵,我們用Long類型是可以使主鍵id自增
    private Long id;
    //@Preoerty這個是數據庫表的列名,nameInDb = "student_name" 是指表中的列名爲“student_name  
    @Property(nameInDb = "student_name")
    private String studentName;;
}

類的屬性寫好之後,這個時候我們只需要編譯一下代碼greenDao 會自動創建類的get、set方法和構造方法,同時會在我們配置的greendao的文件中自動生成DaoMaster、DaoSession和StudentDao.
在這裏插入圖片描述
這裏需要記住,如果你不是第一次新增類的話,在新增完之後是要升級我們greendao配置文件中,我們的數據庫版本號的,負責可能會報錯,這個時候我們只需要把 schemaVersion 它的值加一就可以了

schemaVersion 1//數據庫版本號

接着我們在green_dao這個包下面新建一個DaoManager的類,方便獲取我們的DaoSession,讓我們使用起來更方便,快捷!一下是我們DaoManager的代碼。

public class DaoManager {
    private Context mContext;

    //創建數據庫的名字
    private static final String DB_NAME = "aaa.db";

    //多線程中要被共享的使用volatile關鍵字修飾  GreenDao管理類
    private volatile static DaoManager mInstance;

    //它裏邊實際上是保存數據庫的對象
    private static DaoMaster mDaoMaster;

    //創建數據庫的工具
    private static DaoMaster.DevOpenHelper mHelper;

    //管理gen裏生成的所有的Dao對象裏邊帶有基本的增刪改查的方法
    private static DaoSession mDaoSession;


    private DaoManager() {
    }

    /**
     * 單例模式獲得操作數據庫對象
     *
     * @return
     */
    public static DaoManager getInstance() {
        if (mInstance == null) {
            synchronized (DaoManager.class) {
                if (mInstance == null) {
                    mInstance = new DaoManager();
                }
            }
        }
        return mInstance;
    }

    /**
     * 初始化上下文創建數據庫的時候使用
     */
    public void init(Context context) {
        this.mContext = context;
    }

    /**
     * 判斷是否有存在數據庫,如果沒有則創建
     *
     * @return
     */
    public DaoMaster getDaoMaster() {
        if (mDaoMaster == null) {
            mHelper = new DaoMaster.DevOpenHelper(mContext, DB_NAME, null);
            mDaoMaster = new DaoMaster(mHelper.getWritableDatabase());
        }
        return mDaoMaster;
    }

    /**
     * 完成對數據庫的添加、刪除、修改、查詢操作,
     *
     * @return
     */
    public DaoSession getDaoSession() {
        if (mDaoSession == null) {
            if (mDaoMaster == null) {
                mDaoMaster = getDaoMaster();
            }
            mDaoSession = mDaoMaster.newSession();
        }
        return mDaoSession;
    }

    /**
     * 關閉所有的操作,數據庫開啓後,使用完畢要關閉
     */
    public void closeConnection() {
        closeHelper();
        closeDaoSession();
    }

    public void closeHelper() {
        if (mHelper != null) {
            mHelper.close();
            mHelper = null;
        }
    }

    public void closeDaoSession() {
        if (mDaoSession != null) {
            mDaoSession.clear();
            mDaoSession = null;
        }
    }
}

我們在MyApplication裏面初始化一下我們的DaoManager

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        DaoManager.getInstance().init(this);
        DaoManager.getInstance().getDaoMaster();
    }
}

下面我們就可以使用了!
2 greenDao 新增數據
A 新增一條數據

//獲取StudentDao
	StudentDao studentDao = DaoManager.getInstance().getDaoSession().getStudentDao();
	//新建一個Srudent
	Student student = new Student(null,"張三");//ID可以自增所以我們傳null
	//使用studentDao 新增一個student
	studentDao.insert(student);

B 批量新增

StudentDao  studentDao = DaoManager.getInstance().getDaoSession().getStudentDao();

Student student = new Student(null,"張三");//ID可以自增所以我們傳null
Student student2 = new Student(null,"王五");
List<Student> studentList = new ArrayList<>();
studentList.add(student);
studentList.add(student2);
//批量新增
studentDao.insertInTx(studentList);

greenDao 還有一個方法 insertOrReplace 這個和 insert的使用方法是一樣的,他是插入或替換數據,是根據主鍵來判斷

studentDao.insertOrReplace(student);
studentDao.insertOrReplaceInTx(studentList);

3 greenDao刪除數據

studentDao.delete(student);//刪除一個對象
studentDao.deleteAll();//刪除所有
studentDao.deleteByKey(1l);//根據主鍵刪除一條數據
List<Long> idList = new ArrayList<>();
studentDao.deleteByKeyInTx(idList);//根據主鍵刪除列表
studentDao.deleteInTx(studentList);//根據刪除列表

4 greenDao 修改數據

//更新單條數據
studentDao.update(student);
//批量更新數據
studentDao.updateInTx(studentList);

5 greenDao 查詢數據

	//查詢所有
List<Student> studentSearchList = studentDao.loadAll();
studentSearchList = studentDao.queryBuilder().build().list();
//查詢數據共有多少條
int count = (int) studentDao.count();
count = (int) studentDao.queryBuilder().count();
//更具條件查詢數據

//查詢名字爲張三的所有學生
studentSearchList = studentDao.queryBuilder()
        .where(StudentDao.Properties.StudentName.eq("張三"))
        .build().list();
//查詢一個對象
//查詢Id是1的學生,id具有唯一性,所以查出來是單條數據
Student student_1 = studentDao.queryBuilder()
        .where(StudentDao.Properties.Id.eq(1))
        .build().unique();
//多條件查詢
Student student_2 = studentDao.queryBuilder()
        .where(StudentDao.Properties.Id.eq(1),StudentDao.Properties.StudentName.eq("張三"))
        .build().unique();
Student student_3 = studentDao.queryBuilder()
        .whereOr(StudentDao.Properties.Id.eq(1),StudentDao.Properties.StudentName.eq("張三"))
        .build().unique();
/**
 * greenDao判斷條件
 *
 *  eq 等於
 *  notEq 不等於
 *  like 模糊查詢
 *  between 介於。。。之間
 *  in 包含 可以是一屬性,也可以是集合
 *  notIn 不包含 可以是一屬性,也可以是集合
 *  gt 大於
 *  ge 大於等於
 *  lt 小於
 *  le 小於等於
 *  isNull 爲null
 *  isNotNull 不爲null
 */

/**
 * greenDao 排序
 *
 * orderAsc 升序
 * orderDesc 降序
 * and /or
 */

where 和 whereOr 後面可以跟多個條件

模糊查詢

//        模糊查詢
        studentSearchList = studentDao.queryBuilder()
                .where(StudentDao.Properties.StudentName.like("%張%"))//名字中包含張的學生
                .build().list();

數據排序

//查詢數據排序 升序
studentSearchList = studentDao.queryBuilder()
        .orderAsc(StudentDao.Properties.Id)
        .build().list();
/**
 * greenDao 排序
 *
 * orderAsc 升序
 * orderDesc 降序
 */

分頁查詢

注意page是從0開始的

//        分頁查詢
        int page = 0;//注意page是從0開始的
        studentSearchList= studentDao.queryBuilder().offset(page * 20).limit(20).list();

Over!

如有不明白的可以觀看視頻
https://www.bilibili.com/video/BV1Qt4y117Up

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章