Android數(shù)據(jù)庫-GreenDao

簡介

greenDao是一個將對象映射到SQLite數(shù)據(jù)庫中的輕量且快速的ORM解決方案虾宇。

我認為GreenDao絕對是目前最好用的Android數(shù)據(jù)庫框架,性能很強厚脉,但是我覺得它最大的優(yōu)點是易用攀细。自從用了GreenDao我都不會寫SQL了寂曹,媽媽表示非常擔心我的SQL知識是否會遺忘干凈。

GitHub:https://github.com/greenrobot/greenDAO
官網(wǎng):http://greenrobot.org/greendao/

使用

1衬潦、導包

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

2斤蔓、Gradle配置

apply plugin: 'org.greenrobot.greendao'
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.1'
    }
}

3、數(shù)據(jù)庫配置

greendao {
    schemaVersion 1
    daoPackage 'com.asksky.greendao'
    targetGenDir 'src/main/java'
}

說明:
schemaVersion:指定數(shù)據(jù)庫版本號别渔,每次數(shù)據(jù)庫表改動只需要在此修改一下版本號附迷,GreenDao就會自動進行相應的表升級操作
daoPackage:dao的包名,包名默認是entity所在的包
targetGenDir:生成庫文件的目錄哎媚,默認為build/generated/source/greendao
generateTests:設置為true可以自動生成單元測試
targetGenDirTests:設置單元測試生成的目錄喇伯,默認為src/androidTest/java
以上參數(shù)除schemaVersion都可以使用默認的,無需配置拨与。generateTests默認false

4稻据、實體類和注解

@Entity
public class User {
    @Id
    private Long id;
    private String name;
    @Transient
    private int tempUsageCount; // not persisted
 
   // getters and setters for id and user ...
}
  • @Entity注解的Java類回自動轉(zhuǎn)化為一個數(shù)據(jù)庫支持的實體類。同時會在重新編譯后自動生成Get买喧、Set方法捻悯。
  • 實體類中的所有字段的類型不能是常用數(shù)據(jù)類型。int -> Integer 淤毛、 long->Long
  • 使用@Transient可以讓GreenDao忽略某一變量

5今缚、基本使用

/**
 * Created by AskSky on 2016/11/22.
 * 數(shù)據(jù)庫輔助類
 */

public class DBHelper {
    private static final String TAG = DBHelper.class.getSimpleName();
    private static DBHelper mInstance;
    private DaoMaster.DevOpenHelper mOpenHelper;
    private DaoMaster mDaoMaster;
    private DaoSession mDaoSession;
    private String password = "AskSky_TanPeiQi_1195211669_JMSQJ";
    private static final String DBName = "testDb";

    private DBHelper() {
    }

    public static DBHelper getInstance() {
        if (mInstance == null) {
            mInstance = new DBHelper();
        }
        return mInstance;
    }

    public void init(Context context) {
        mOpenHelper = new DaoMaster.DevOpenHelper(context, DBName, null);
        mDaoMaster = new DaoMaster(mOpenHelper.getEncryptedWritableDb(Utils.getMd5(password)));
        mDaoSession = mDaoMaster.newSession();
    }

    public DaoSession getSession() {
        return mDaoSession;
    }

    public DaoMaster getMaster() {
        return mDaoMaster;
    }

}

**說明:
不要忘記在Application中調(diào)用init()方法初始化
mDaoMaster = new DaoMaster(mOpenHelper.getEncryptedWritableDb(Utils.getMd5(password)));這一行是開啟數(shù)據(jù)庫加密,若要使用數(shù)據(jù)庫加密低淡,需要導入:
compile 'net.zetetic:android-database-sqlcipher:3.5.4@aar'
**

6 姓言、增刪改查


  • DBHelper.getInstance().getSession().getUserDao().insert(mUser);
//DBHelper.getInstance().getSession().getUserDao().deleteByKey(mUser.getId());
//DBHelper.getInstance().getSession().getUserDao().delete(mUser);
DBHelper.getInstance().getSession().getUserDao().deleteAll();

  • DBHelper.getInstance().getSession().update(mUser);

  • List<User> users = DBHelper.getInstance().getSession().getUserDao().loadAll();
    很明顯,增刪改查簡單的過分

7蔗蹋、其他注解

@Entity注解的細節(jié)配置:

@Entity(
        // If you have more than one schema, you can tell greenDAO
        // to which schema an entity belongs (pick any string as a name).
        schema = "myschema",

        // Flag to make an entity "active": Active entities have update,
        // delete, and refresh methods.
        active = true,
        
        // Specifies the name of the table in the database.
        // By default, the name is based on the entities class name.
        nameInDb = "AWESOME_USERS",
        
        // Define indexes spanning multiple columns here.
        indexes = {
                @Index(value = "name DESC", unique = true)
        },
        
        // Flag if the DAO should create the database table (default is true).
        // Set this to false, if you have multiple entities mapping to one table,
        // or the table creation is done outside of greenDAO.
        createInDb = false,

        // Whether an all properties constructor should be generated.
        // A no-args constructor is always required.
        generateConstructors = true,

        // Whether getters and setters for properties should be generated if missing.
        generateGettersSetters = true
)
public class User {
  ...
}
  • @Entity 定義實體
  • @nameInDb 在數(shù)據(jù)庫中的名字何荚,如不寫則為實體中類名
  • @indexes 索引
  • @createInDb 是否創(chuàng)建表,默認為true,false時不創(chuàng)建
  • @schema 指定架構(gòu)名稱為實體
  • @active 無論是更新生成都刷新

8猪杭、成員變量參數(shù)配置

@Entity
public class User {
    @Id(autoincrement = true)
    private Long id;
 
    @Property(nameInDb = "USERNAME")
    private String name;
 
    @NotNull
    private int repos;
 
    @Transient
    private int tempUsageCount;
 
    ...
}
  • @Id 主鍵 參數(shù)autoincrement表示是否自增長
  • @Property 列名 nameInDb制定具體列名
  • @NotNull 非空
  • @Transient 指定GreenDao忽略此變量

9餐塘、約束

@Entity
public class User {
    @Id private Long id;
    @Index(unique = true)
    private String name;
}
  • @Index 創(chuàng)建數(shù)據(jù)庫索引 unique 添加唯一約束,使所有的值都是唯一的
@Entity
public class User {
    @Id private Long id;
    @Unique private String name;
}
  • @Unique 指定序列使用唯一約束 注意,SQLite還隱式地創(chuàng)建一個索引

總結(jié)

GreenDao是目前比較火的數(shù)據(jù)庫管理框架皂吮,經(jīng)過千千萬萬次驗證戒傻,其穩(wěn)定性和性能自不用說税手,而其易用性也確實很強。本文僅介紹了GreenDao的基本用法需纳,其他高級用法可以去官網(wǎng)查看冈止。如根據(jù)時間倒序查詢前50條數(shù)據(jù)可以這樣寫:

List<Message> data = DBHelper.getInstance().getSession().getMessageDao().queryBuilder()
.orderDesc(MessageDao.Properties.Time).limit(50).list();

我在GitHub上放了一個簡單Demo,大家可以參考一下:
https://github.com/AskSky924/GreenDaoDemo

以上內(nèi)容如有錯誤或不足候齿,歡迎指正熙暴。QQ:1195211669

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市慌盯,隨后出現(xiàn)的幾起案子周霉,更是在濱河造成了極大的恐慌,老刑警劉巖亚皂,帶你破解...
    沈念sama閱讀 222,681評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件俱箱,死亡現(xiàn)場離奇詭異,居然都是意外死亡灭必,警方通過查閱死者的電腦和手機狞谱,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,205評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來禁漓,“玉大人跟衅,你說我怎么就攤上這事〔ゼ撸” “怎么了伶跷?”我有些...
    開封第一講書人閱讀 169,421評論 0 362
  • 文/不壞的土叔 我叫張陵,是天一觀的道長秘狞。 經(jīng)常有香客問我叭莫,道長,這世上最難降的妖魔是什么烁试? 我笑而不...
    開封第一講書人閱讀 60,114評論 1 300
  • 正文 為了忘掉前任雇初,我火速辦了婚禮,結(jié)果婚禮上减响,老公的妹妹穿的比我還像新娘靖诗。我一直安慰自己,他們只是感情好辩蛋,可當我...
    茶點故事閱讀 69,116評論 6 398
  • 文/花漫 我一把揭開白布呻畸。 她就那樣靜靜地躺著移盆,像睡著了一般悼院。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上咒循,一...
    開封第一講書人閱讀 52,713評論 1 312
  • 那天据途,我揣著相機與錄音绞愚,去河邊找鬼。 笑死颖医,一個胖子當著我的面吹牛位衩,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播熔萧,決...
    沈念sama閱讀 41,170評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼糖驴,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了佛致?” 一聲冷哼從身側(cè)響起贮缕,我...
    開封第一講書人閱讀 40,116評論 0 277
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎俺榆,沒想到半個月后感昼,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,651評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡罐脊,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,714評論 3 342
  • 正文 我和宋清朗相戀三年定嗓,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片萍桌。...
    茶點故事閱讀 40,865評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡宵溅,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出上炎,到底是詐尸還是另有隱情层玲,我是刑警寧澤,帶...
    沈念sama閱讀 36,527評論 5 351
  • 正文 年R本政府宣布反症,位于F島的核電站辛块,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏铅碍。R本人自食惡果不足惜润绵,卻給世界環(huán)境...
    茶點故事閱讀 42,211評論 3 336
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望胞谈。 院中可真熱鬧尘盼,春花似錦、人聲如沸烦绳。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,699評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽径密。三九已至午阵,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背底桂。 一陣腳步聲響...
    開封第一講書人閱讀 33,814評論 1 274
  • 我被黑心中介騙來泰國打工植袍, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人籽懦。 一個月前我還...
    沈念sama閱讀 49,299評論 3 379
  • 正文 我出身青樓于个,卻偏偏與公主長得像,于是被迫代替她去往敵國和親暮顺。 傳聞我的和親對象是個殘疾皇子厅篓,可洞房花燭夜當晚...
    茶點故事閱讀 45,870評論 2 361

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

  • 現(xiàn)在有個需求。需要存入很多數(shù)據(jù)到數(shù)據(jù)庫中捶码,并且要求加密贷笛。于是用到了GreenDao3.0 首先各種導庫 在modu...
    基本密碼宋閱讀 3,768評論 1 5
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,328評論 25 707
  • 一、關(guān)于greenDAO greenDAO應該算是當前最火的數(shù)據(jù)庫開源框架了宙项,它是一個將對象映射到SQLite數(shù)據(jù)...
    當幸福來敲門58閱讀 13,881評論 3 19
  • 我非常尊敬和崇拜魯迅先生乏苦,此文根據(jù)事實而寫,沒有褒貶尤筐。正如先生所言:“倘要完全的書汇荐,天下可讀的書怕要絕無,倘要完全...
    先生在沒意外閱讀 140評論 0 0
  • (一) 我只記得當時很累盆繁,累的走路都沒有力氣了掀淘,連晚飯都沒吃就去睡覺了。那一覺睡的不太好油昂,而且還做了一個夢革娄,夢見在...
    或曰閱讀 639評論 0 1