greenDao基本使用步驟

greenDao基本使用步驟



  • 第一步:接入jar包
  1. app的build.gradle中

dependencies 的節(jié)點(diǎn)下添加依賴

compile 'org.greenrobot:greendao:3.2.2'
compile 'org.greenrobot:greendao-generator:3.2.2'
  1. 在project的build.gradle中

buildscript 下的 dependencies中添加

 classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'

allprojects 下的 repositories 中添加

mavenCentral() // add repository
  1. 新建的AndroidLib庫中

lib 的build.gradle 中最上面添加:

apply plugin: 'org.greenrobot.greendao'

在android節(jié)點(diǎn)下添加:greendao配置文件

greendao {
        schemaVersion 2
        daoPackage 'com.mrko.dao'
        targetGenDir 'src/main/java'
    }

dependencies 節(jié)點(diǎn)下添加:greenDao依賴

compile 'org.greenrobot:greendao:3.2.2'
compile 'org.greenrobot:greendao-generator:3.2.2'
  1. 將新建的AndroidLib庫依賴到APP項(xiàng)目中、

  • 第二步:新建AndroidLib。實(shí)現(xiàn)封裝Utils

只有建立完成之后才能去進(jìn)行build.gradle配置(也就是第一步的3.4點(diǎn))

  1. 新建一個(gè)module-->選擇Android jar。
  2. 進(jìn)行第一步中的序號(hào)3進(jìn)行g(shù)radle的配置。
  3. 新建一個(gè)DBApplication。代碼如下

DBApplication這繼承的是app的Application
本身AndroidManifest.xml不做處理

package com.mrko;
import android.app.Application;
import com.mrko.dao.DaoMaster;
import com.mrko.dao.DaoSession;
import org.greenrobot.greendao.database.Database;

/**
 * Created by Mrko on 2017/9/19-10:16.
 * Email:mrko0630@163.com
 */

public class DBApplication extends Application {
    //定義數(shù)據(jù)庫名稱
    public static final String DB_NAME = "Stuent.db";
    private DaoSession session;
    //獲取本地的一個(gè)實(shí)例
    private static DBApplication DBApplication;

    @Override
    public void onCreate() {
        super.onCreate();
        DBApplication = this;
        initDB();
    }

    /**
     * 初始化
     * 1.先獲取DexOpenHelper的實(shí)例。新建一個(gè)數(shù)據(jù)庫表
     * 2.獲取dataBase的寫入權(quán)限
     * 3.新建一個(gè)DaoMaster類曹宴。將dataBase交給其管理
     * 4.獲取到Session的實(shí)例(session就是操作數(shù)據(jù)庫的直接類)
     */
    public void initDB() {
        DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(this, DB_NAME);
        Database database = devOpenHelper.getWritableDb();
        DaoMaster daoMaster = new DaoMaster(database);
        session = daoMaster.newSession();
    }

    public static DBApplication getAPPlication() {
        return DBApplication;
    }

    public synchronized DaoSession getDaoSession() {
        if (session == null) {
            initDB();
        }
        return session;
    }
}


  • 第三步:新建實(shí)體類、也就是數(shù)據(jù)庫表中所需要字段。

Student 類。

  1. 開始新建時(shí)候代碼如下:
package com.mrko.mydb;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Property;

/**
 * Created by Mrko on 2017/9/19-10:00.
 * Email:mrko0630@163.com
 */

@Entity
public class Student {
    //注意 是Long 不是long 
    @Id(autoincrement = true)
    private Long id;

    @Property(nameInDb = "name")
    private String name;

    @Property(nameInDb = "age")
    private int age;

    
}

  1. 然后在Make project (點(diǎn)擊小錘子)
  2. 新生成代碼如下:并會(huì)在build.gradle中配置的地址(targetGenDir 'src/main/java')的目錄下生成三個(gè)實(shí)體類(DaoMaster、DaoSession、StudentDao)(一般添加新的字段【诨溃可以把之前生成的三個(gè)實(shí)體類刪除魁巩,重新生成)
package com.mrko.mydb;

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

/**
 * Created by Mrko on 2017/9/19-10:00.
 * Email:mrko0630@163.com
 */

@Entity
public class Student {
    //注意 是Long 不是long
    @Id(autoincrement = true)
    private Long id;

    @Property(nameInDb = "name")
    private String name;

    @Property(nameInDb = "age")
    private int age;

    @Generated(hash = 352757281)
    public Student(Long id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    @Generated(hash = 1556870573)
    public Student() {
    }

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

    
    
}

  • 第四步:新建數(shù)據(jù)庫工具類

    DBUtils 數(shù)據(jù)庫統(tǒng)一管理實(shí)現(xiàn)封裝

package com.mrko.helper;

import android.util.Log;

import com.mrko.DBApplication;
import com.mrko.dao.DaoSession;
import com.mrko.dao.StudentDao;
import com.mrko.mydb.Student;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.List;

import static android.content.ContentValues.TAG;

/**
 * Created by Mrko on 2017/9/19-10:35.
 * Email:mrko0630@163.com
 */

public class DBStudentUtils {
    private static DaoSession mDaoSession;
    private static StudentDao mStuentDao;
    private static DBStudentUtils instance = null;

    private DBStudentUtils() {

    }

    /**
     * 雙重校驗(yàn)鎖單例模式
     * 實(shí)例化Session和Dao類
     * @return
     */
    public static DBStudentUtils getInstance() {
        if (instance == null) {
            synchronized (DBStudentUtils.class) {
                if (instance == null) {
                    instance = new DBStudentUtils();
                }
                mDaoSession = DBApplication.getAPPlication().getDaoSession();
                mStuentDao = mDaoSession.getStudentDao();
            }
        }
        return instance;
    }

    public Student makeStudent(String name, int age) {
        Student student = null;
        if (student == null) {
            student = new Student();
            Log.e(TAG, "makeStudent: " + student.getId());
            student.setName(name);
            student.setAge(age);
            insertStudent(student);
        }
        return student;
    }

    public void insertStudent(Student student) {
        mStuentDao.insert(student);
    }

    public void updateStudent(Student student) {
        mStuentDao.update(student);
    }

    public void deleteStudent(Long id) {
        mStuentDao.deleteByKey(id);
    }

    public List<Student> queryStudent(int age) {
        QueryBuilder<Student> queryBuilder = mStuentDao.queryBuilder();
        queryBuilder.where(StudentDao.Properties.Age.gt(age));
        List<Student> queryStudents = queryBuilder.list();
        return queryStudents;
    }

}

  • 第五步:如何調(diào)用:
package com.mrko.testone.dao;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.mrko.helper.DBStudentUtils;
import com.mrko.mydb.Student;
import com.mrko.testone.R;
import com.socks.library.KLog;

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

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class DaoTestTwoActivity extends Activity {

    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_age)
    EditText etAge;
    @BindView(R.id.btn_save)
    Button btnSave;
    @BindView(R.id.btn_update)
    Button btnUpdate;
    @BindView(R.id.btn_delete)
    Button btnDelete;
    @BindView(R.id.btn_query)
    Button btnQuery;
    @BindView(R.id.listview)
    ListView listview;
    private Unbinder unbinder;
    private String mName;
    private int mAge;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dao_test_two);
        unbinder = ButterKnife.bind(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }

    @OnClick({R.id.btn_save, R.id.btn_update, R.id.btn_delete, R.id.btn_query})
    public void onViewClicked(View view) {
        mName = etName.getText().toString().trim();
        String temp = etAge.getText().toString().trim();
        mAge = Integer.parseInt(temp == null || temp.equals("") ? "0" : temp);
        switch (view.getId()) {
            case R.id.btn_save:
                DBStudentUtils.getInstance().makeStudent(mName, mAge);
                break;
            case R.id.btn_update:
                DBStudentUtils.getInstance().makeStudent(mName, mAge);
                break;
            case R.id.btn_delete:
                List<Student> queryStudent = DBStudentUtils.getInstance().queryStudent(mAge);
                List<Long> deleteStudents= new ArrayList<>();
                if (queryStudent != null) {
                    for (Student student : queryStudent) {
                        KLog.e("mrko--->",student.getId() + "--" + student.getAge() + "--" + student.getName());
                        deleteStudents.add(student.getId());
                    }
                    if (deleteStudents!=null){
                        for(Long id : deleteStudents) {
                            DBStudentUtils.getInstance().deleteStudent(id);
                            KLog.e("mrko--->","delete id-->"+id);
                        }
                    }

                }
                break;
            case R.id.btn_query:
                List<Student> queryStudents = DBStudentUtils.getInstance().queryStudent(mAge);
                if (queryStudents != null) {
                    for (Student student : queryStudents) {
                        KLog.e("mrko--->" + student.getId() + "--" + student.getAge() + "--" + student.getName());
                    }
                }
                break;
        }
    }
}

  • 第六步:注意事項(xiàng):

DBApplication需要在app的AndroidManifest.xml中實(shí)現(xiàn)android:name.. 如果重寫application,繼承DBAapplication、


基本接入步驟如上踏枣、當(dāng)然greenDao很多探究躬厌、這里只是入門操作、笛谦、班門弄斧而已懦冰、

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市赋除,隨后出現(xiàn)的幾起案子敞嗡,更是在濱河造成了極大的恐慌,老刑警劉巖键畴,帶你破解...
    沈念sama閱讀 222,183評(píng)論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件问词,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡宛篇,警方通過查閱死者的電腦和手機(jī)豺瘤,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,850評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門须妻,熙熙樓的掌柜王于貴愁眉苦臉地迎上來掌逛,“玉大人动知,你說我怎么就攤上這事。” “怎么了讼油?”我有些...
    開封第一講書人閱讀 168,766評(píng)論 0 361
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)确虱。 經(jīng)常有香客問我扎唾,道長(zhǎng),這世上最難降的妖魔是什么概疆? 我笑而不...
    開封第一講書人閱讀 59,854評(píng)論 1 299
  • 正文 為了忘掉前任使套,我火速辦了婚禮厌杜,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘馁痴。我一直安慰自己,他們只是感情好茫叭,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,871評(píng)論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著朽缎,像睡著了一般最筒。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上虏冻,一...
    開封第一講書人閱讀 52,457評(píng)論 1 311
  • 那天,我揣著相機(jī)與錄音践磅,去河邊找鬼肺樟。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的欣舵。 我是一名探鬼主播,決...
    沈念sama閱讀 40,999評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼垂寥,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼夭坪!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起赏殃,我...
    開封第一講書人閱讀 39,914評(píng)論 0 277
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,465評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡逮栅,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,543評(píng)論 3 342
  • 正文 我和宋清朗相戀三年捧存,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,675評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡害淤,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤决摧,帶...
    沈念sama閱讀 36,354評(píng)論 5 351
  • 正文 年R本政府宣布,位于F島的核電站则拷,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜笙纤,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,029評(píng)論 3 335
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦惋戏、人聲如沸舔亭。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,514評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽冈钦。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間绢片,已是汗流浹背熙涤。 一陣腳步聲響...
    開封第一講書人閱讀 33,616評(píng)論 1 274
  • 我被黑心中介騙來泰國(guó)打工茸歧, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留涤浇,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 49,091評(píng)論 3 378
  • 正文 我出身青樓纵顾,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親曹仗。 傳聞我的和親對(duì)象是個(gè)殘疾皇子遭居,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,685評(píng)論 2 360

推薦閱讀更多精彩內(nèi)容