GreenDao3.0+庫,輕鬆搞定安卓數據庫操作

GreenDao是安卓的數據庫操作庫,它實現了ORM,ORM稱爲:對象關係映射
我把它簡單的理解爲用對象來操作數據庫
比如我需要創建一個User名字的數據庫表,我可以直接定義一個User類,裏面加上倆個參數
age,name,導入GreenDao庫後,我只需要在User類上面加上一個@Entity註解
像這樣

@Entity
public class User {
    @Id(autoincrement = true)
    private Long id;
    private String name;
    private int age;

然後make一下項目,User表就生成了,同時表中帶有age和name的屬性,
再比如我們需要往表中插入一個數據,那麼只需要

User user= new User("sweet","20");
dao.insert(user);

這樣就實現了數據的插入操作,怎麼樣是不是很簡單?
這裏有個dao對象是怎麼來的呢?
好了,正式進入正文,首先回顧下我們以前使用sqlite操作數據庫的時候是怎麼樣的
首先:

package com.demo.swt.mystudyappshop.Wight;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * 介紹:這裏寫介紹
 * 作者:sweet
 * 郵箱:[email protected]
 * 時間: 2017/2/10
 */

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final int VERSION = 1;

    //在SQLiteOepnHelper的子類當中,必須有該構造函數
    public DatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory,
                          int version) {
        //必須通過super調用父類當中的構造函數
        super(context, name, factory, version);
    }

    public DatabaseHelper(Context context, String name) {
        this(context, name, VERSION);
    }

    public DatabaseHelper(Context context, String name, int version) {
        this(context, name, null, version);
    }

    //該函數是在第一次創建數據庫的時候執行,實際上是在第一次得到SQLiteDatabse對象的時候,纔會調用這個方法
    @Override
    public void onCreate(SQLiteDatabase db) {
        System.out.println("create a Database");
        //execSQL函數用於執行SQL語句
        db.execSQL("create table user(id int,name varchar(20))");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        System.out.println("update a Database");
    }
}

我們需要創建一個helper類繼承SQLiteOpenHelper 同時在裏面定義數據庫的版本號,同時還得自己寫數據庫語句
db.execSQL(“create table user(id int,name varchar(20))”);
這裏有個db是SQLiteDatabase 的對象,
接下來創建好helper類之後
創建數據庫

 //創建一個DatabaseHelper對象
            if (dbHelper == null) {
                dbHelper = new DatabaseHelper(SqliteDataBaseActivity.this, "test_mars_db", 3);
                //只有調用了DatabaseHelper對象的getReadableDatabase()方法,或者是getWritableDatabase()方法之後,纔會創建,或打開一個數據庫
                db = dbHelper.getReadableDatabase();
                db.getVersion();
            } else {
                dataview.setText("你已經創建過數據庫");
            }

插入數據

 if (dbHelper == null) {
                dataview.setText("請先更新數據庫");
            } else {
                //生成ContentValues對象
                ContentValues values = new ContentValues();
                //想該對象當中插入鍵值對,其中鍵是列名,值是希望插入到這一列的值,值必須和數據庫當中的數據類型一致
                values.put("id", 1);
                values.put("name", "zhangsan");
                //調用insert方法,就可以將數據插入到數據庫當中
                db.insert("user", null, values);
            }

大概就實列這倆個就可以看出,sqlite操作數據庫遠遠沒有我們使用greenDao庫操作方便,
說了這麼多,也對比了sqlite和greendao,分析了greendao的好處

這裏還得說一句,本篇使用的是3.0+的GreenDao,3.0後的庫和3.0之前的有很大的不用,3.0後的greendao庫不需要添加外部依賴,用java代碼生成輔助類
直接用註解的方式生成輔助類,並在app的build 中能指定生成的文件的目錄
接下來正式接入
首先在project的build中加入classpath

  dependencies {
        classpath 'com.android.tools.build:gradle:2.2.2'
        //add
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.1'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }

接下來配置app的build
頂部的
apply下面加入這一句

apply plugin: 'org.greenrobot.greendao'

dependencies下加入

  compile 'org.greenrobot:greendao:3.2.0'
    compile 'org.greenrobot:greendao-generator:3.0.0'

最外層配置

//指定生成的文件目錄
greendao {
    schemaVersion 1
    daoPackage 'com.anye.greendao.gen'
    targetGenDir 'src/main/java'
}

全部代碼如下
新增加的我會加入//add

apply plugin: 'com.android.application'
//add
apply plugin: 'org.greenrobot.greendao'
android {
    compileSdkVersion 25
    buildToolsVersion "25.0.1"
    defaultConfig {
        applicationId "com.anlaiye.swt.greendaodemo"
        minSdkVersion 14
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

}
//add
greendao {
    schemaVersion 1
    daoPackage 'com.anye.greendao.gen'
    targetGenDir 'src/main/java'
}



dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.0.1'
    testCompile 'junit:junit:4.12'
    //add
    compile 'org.greenrobot:greendao:3.2.0'
    compile 'org.greenrobot:greendao-generator:3.0.0'
    compile 'com.android.support:recyclerview-v7:25.0.0'

}

到這裏基本的配置就完成了
接下來創建一個user類

@Entity
public class User {
//表示id會自增長
    @Id(autoincrement = true)
    private Long id;
    private String name;
    private int age;
    private String sex;
    }

因爲3.0後都是使用註解的方式,所以如果大家對別的註解像深入瞭解的話可以去官網看下
創建好後點擊build-make
會在我們指定的目錄下生成特定的文件
這裏寫圖片描述
同時在User類中會自動生成get set方法

package com.anlaiye.swt.greendaodemo;

import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Generated;

/**
 * 介紹:這裏寫介紹
 * 作者:sweet
 * 郵箱:[email protected]
 * 時間: 2017/3/9
 */
@Entity
public class User {
    @Id(autoincrement = true)
    private Long id;
    private String name;
    private int age;
    private String sex;
    @Generated(hash = 689493095)
    public User(Long id, String name, int age, String sex) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.sex = sex;
    }
    @Generated(hash = 586692638)
    public User() {
    }
    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 int getAge() {
        return this.age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getSex() {
        return this.sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }


}

接下來進行測試
在前面有個dao對象,現在來看下他是怎麼生成的

   private DaoMaster.DevOpenHelper mHelper;
    private SQLiteDatabase db;
    private DaoMaster mDaoMaster;
    private DaoSession mDaoSession;
       private UserDao dao;
  private void openDb() {
          //創建swt_db的數據庫
        mHelper = new DaoMaster.DevOpenHelper(this, "swt-db", null);
        //拿到可讀可寫的對象
        db = mHelper.getWritableDatabase();
        //拿到DaoMaster對象
        mDaoMaster = new DaoMaster(db);
        //拿到daosession對象
        mDaoSession = mDaoMaster.newSession();
        //創建了user表所以會生成usedao的實例
        dao = mDaoSession.getUserDao();
    }

上面的操作是固定的,也就是說我們可以把打開數據庫的這一系列操作,封裝起來,比如放到aplication中
或者使用一個util類封裝,
好了,拿到了user表的dao對象,接下來就可以正式對user表進行操作了
我寫了一個簡陋的ui來形象的展示
首先看下我寫的DEMO界面效果
這裏寫圖片描述

我定義了3個edittext拿到輸入的值作爲user表的屬性
首先是插入操作

//這裏不用設置id,id設置了自增加,會自動生成
 User insertUser = new User(null, getEtName(), getAge(), getSex());
                    dao.insert(insertUser);

刪除操作

//根據id刪除內容
  dao.deleteByKey(getId());

更新操作

//根據id更新指定的數據
   User UpdateUser = new User(getid(), getEtName(), getAge(), getSex());
                dao.update(UpdateUser);

查詢操作

//查詢出所有的數據
  dao.loadAll();

增刪改查基本上都是一倆句話就完成了
真的是灰常簡單
接下來看下正常的效果
這裏寫圖片描述
這裏只是簡單的使用recyclerview實現做個演示
代碼下載地址
https://github.com/swtandyz/GreenDaoDemo
隨手start thanks

發佈了46 篇原創文章 · 獲贊 37 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章