GreenDao3.2的基本使用方法
前言
GreenDao是一款操作數(shù)據(jù)庫(kù)的神器,經(jīng)過(guò)了2.0版本的升級(jí)后,已經(jīng)被廣泛的開(kāi)發(fā)者使用。確實(shí)是很好用,入門簡(jiǎn)單,可以剩去了數(shù)據(jù)庫(kù)的建表操作和數(shù)據(jù)庫(kù)SQL的編寫,博主用了一次之后愛(ài)不釋手,和以前的數(shù)據(jù)庫(kù)操作一大堆的代碼將它縮成了一句話,舒服.
GreenDao3.2的簡(jiǎn)介
認(rèn)識(shí)GreenDao之前必須知道ORM(Object Relation Mapping對(duì)象關(guān)系映射),其表現(xiàn)形式就是通過(guò)GreenDao將數(shù)據(jù)庫(kù)和Bean對(duì)象關(guān)聯(lián)起來(lái),其表現(xiàn)形式如下圖
GreenDao之所以很流行,跟它的優(yōu)點(diǎn)是息息相關(guān)的,從官網(wǎng)中可以看到這樣一張圖,其表示了在主流的ORM第三方庫(kù)中,其對(duì)數(shù)據(jù)庫(kù)操作的速度是最快的
不僅如此,其優(yōu)點(diǎn)還包括有以下幾點(diǎn)
存取速度快
支持?jǐn)?shù)據(jù)庫(kù)加密
輕量級(jí)
激活實(shí)體
支持緩存
代碼自動(dòng)生成
GreenDao3.2的配置
GreenDao的配置很簡(jiǎn)單,不過(guò)需要注意的是,有些人按照正確的配置后卻頻頻出錯(cuò),個(gè)人也經(jīng)歷過(guò),最后的原因是網(wǎng)絡(luò)有問(wèn)題。因?yàn)樾@網(wǎng)的DNS服務(wù)很差,所以解析不到GreenDao的依賴網(wǎng)站
一、需要在工程(Project)的build.gradle中添加依賴
buildscript {repositories {jcenter()}dependencies {classpath 'com.android.tools.build:gradle:2.0.0'//GreenDao3依賴classpath 'org.greenrobot:greendao-gradle-plugin:3.2.1'} }二、在項(xiàng)目(Module)的build.gradle中添加依賴
apply plugin: 'com.android.application' //使用greendaoapply plugin: 'org.greenrobot.greendao'android {compileSdkVersion 23buildToolsVersion "23.0.2"defaultConfig {applicationId "com.handsome.didi"minSdkVersion 14targetSdkVersion 23versionCode 1versionName "1.0"}//greendao配置greendao {//版本號(hào),升級(jí)時(shí)可配置schemaVersion 1 }buildTypes {release {minifyEnabled falseproguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'}} }dependencies {compile fileTree(include: ['*.jar'], dir: 'libs')testCompile 'junit:junit:4.12'compile 'com.android.support:appcompat-v7:23.1.1'//greendao依賴compile 'org.greenrobot:greendao:3.2.0' }到這里就配置成功了
一、創(chuàng)建Bean對(duì)象(表名和字段名)
@Entity public class Bean {/*** 表示為購(gòu)物車列表*/public static final int TYPE_CART = 0x01;/*** 表示為收藏列表*/public static final int TYPE_LOVE = 0x02;/*** 不能用int*/@Id(autoincrement = true)private Long id;/*** 商品名稱*/@Uniqueprivate String name;/***商品價(jià)格*/@Property(nameInDb = "price")private String price;/*** 已售數(shù)量*/private int sell_num;/*** 圖標(biāo)url*/private String image_url;/*** 商家地址*/private String address;/*** 商品列表類型*/private int type; }點(diǎn)擊Build后make project后GreenDao會(huì)自動(dòng)幫你生成get/set方法如下:
package com.tongseng.sqlitedemo.generate;import org.greenrobot.greendao.annotation.Entity; import org.greenrobot.greendao.annotation.Id; import org.greenrobot.greendao.annotation.Property; import org.greenrobot.greendao.annotation.Unique; import org.greenrobot.greendao.annotation.Generated;/*** com.tongseng.sqlitedemo.generate** @author Administrator* @date 2018/3/21*/ @Entity public class Bean {/*** 表示為購(gòu)物車列表*/public static final int TYPE_CART = 0x01;/*** 表示為收藏列表*/public static final int TYPE_LOVE = 0x02;/*** 不能用int*/@Id(autoincrement = true)private Long id;/*** 商品名稱*/@Uniqueprivate String name;/***商品價(jià)格*/@Property(nameInDb = "price")private String price;/*** 已售數(shù)量*/private int sell_num;/*** 圖標(biāo)url*/private String image_url;/*** 商家地址*/private String address;/*** 商品列表類型*/private int type;@Generated(hash = 139605306)public Bean(Long id, String name, String price, int sell_num, String image_url,String address, int type) {this.id = id;this.name = name;this.price = price;this.sell_num = sell_num;this.image_url = image_url;this.address = address;this.type = type;}@Generated(hash = 80546095)public Bean() {}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 getPrice() {return this.price;}public void setPrice(String price) {this.price = price;}public int getSell_num() {return this.sell_num;}public void setSell_num(int sell_num) {this.sell_num = sell_num;}public String getImage_url() {return this.image_url;}public void setImage_url(String image_url) {this.image_url = image_url;}public String getAddress() {return this.address;}public void setAddress(String address) {this.address = address;}public int getType() {return this.type;}public void setType(int type) {this.type = type;} }這里需要注意的是,創(chuàng)建完成之后,需要build gradle來(lái)完成我們的代碼自動(dòng)生成。自動(dòng)生成的代碼有
1. Bean實(shí)體的構(gòu)造方法和get、set方法
2. DaoMaster、DaoSession、DAOS類
這里對(duì)Bean對(duì)象的注釋進(jìn)行解釋
@Entity:告訴GreenDao該對(duì)象為實(shí)體,只有被@Entity注釋的Bean類才能被dao類操作
@Id:對(duì)象的Id,使用Long類型作為EntityId,否則會(huì)報(bào)錯(cuò)。(autoincrement = true)表示主鍵會(huì)自增,如果false就會(huì)使用舊值
@Property:可以自定義字段名,注意外鍵不能使用該屬性
@NotNull:屬性不能為空
@Transient:使用該注釋的屬性不會(huì)被存入數(shù)據(jù)庫(kù)的字段中
@Unique:該屬性值必須在數(shù)據(jù)庫(kù)中是唯一值
@Generated:編譯后自動(dòng)生成的構(gòu)造函數(shù)、方法等的注釋,提示構(gòu)造函數(shù)、方法等不能被修改
二、創(chuàng)建數(shù)據(jù)庫(kù)(數(shù)據(jù)庫(kù)名)
數(shù)據(jù)庫(kù)的表名和字段都建好了,下面差個(gè)數(shù)據(jù)庫(kù)的創(chuàng)建,下面通過(guò)傳統(tǒng)和GreenDao的比較來(lái)體驗(yàn)其優(yōu)點(diǎn)
public class BaseApplication extends Application {private static DaoSession daoSession;@Overridepublic void onCreate() {super.onCreate();//配置數(shù)據(jù)庫(kù)setupDatabase();}/*** 配置數(shù)據(jù)庫(kù)*/private void setupDatabase() {//創(chuàng)建數(shù)據(jù)庫(kù)shop.db"DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "shop.db", null);//獲取可寫數(shù)據(jù)庫(kù)SQLiteDatabase db = helper.getWritableDatabase();//獲取數(shù)據(jù)庫(kù)對(duì)象DaoMaster daoMaster = new DaoMaster(db);//獲取Dao對(duì)象管理者daoSession = daoMaster.newSession();}public static DaoSession getDaoInstant() {return daoSession;} }可以發(fā)現(xiàn),GreenDao已經(jīng)將我們的數(shù)據(jù)庫(kù)創(chuàng)建縮成幾句話,代碼會(huì)自動(dòng)將Bean對(duì)象創(chuàng)建成表,不再是傳統(tǒng)的手寫SQL語(yǔ)句。這里的數(shù)據(jù)庫(kù)創(chuàng)建只需要在Application中執(zhí)行一次即可,這里對(duì)幾個(gè)類進(jìn)行解釋
DevOpenHelper:創(chuàng)建SQLite數(shù)據(jù)庫(kù)的SQLiteOpenHelper的具體實(shí)現(xiàn)
DaoMaster:GreenDao的頂級(jí)對(duì)象,作為數(shù)據(jù)庫(kù)對(duì)象、用于創(chuàng)建表和刪除表
DaoSession:管理所有的Dao對(duì)象,Dao對(duì)象中存在著增刪改查等API
由于我們已經(jīng)創(chuàng)建好了DaoSession和Bean的Bean對(duì)象,編譯后會(huì)自動(dòng)生成我們的BeanDao對(duì)象,可通過(guò)DaoSession獲得
BeanDao dao = daoSession.getBeanDao();
這里的Dao(Data Access Object)是指數(shù)據(jù)訪問(wèn)接口,即提供了數(shù)據(jù)庫(kù)操作一些API接口,可通過(guò)dao進(jìn)行增刪改查操作
三、數(shù)據(jù)庫(kù)的增刪改查
數(shù)據(jù)庫(kù)的表名、字段、數(shù)據(jù)庫(kù)都建好了,下面就通過(guò)GreenDao對(duì)數(shù)據(jù)庫(kù)進(jìn)行操作
public class LoveDao {/*** 添加數(shù)據(jù),如果有重復(fù)則覆蓋** @param shop*/public static void insertLove(Shop shop) {BaseApplication.getDaoInstant().getShopDao().insertOrReplace(shop);}/*** 刪除數(shù)據(jù)** @param id*/public static void deleteLove(long id) {BaseApplication.getDaoInstant().getShopDao().deleteByKey(id);}/*** 更新數(shù)據(jù)** @param shop*/public static void updateLove(Shop shop) {BaseApplication.getDaoInstant().getShopDao().update(shop);}/*** 查詢條件為Type=TYPE_LOVE的數(shù)據(jù)** @return*/public static List<Shop> queryLove() {return BaseApplication.getDaoInstant().getShopDao().queryBuilder().where(ShopDao.Properties.Type.eq(Shop.TYPE_LOVE)).list();}/*** 查詢?nèi)繑?shù)據(jù)*/public static List<Shop> queryAll() {return BaseApplication.getDaoInstant().getShopDao().loadAll();} }效果很明顯,GreenDao的封裝更加短小精悍,語(yǔ)義明朗,下面對(duì)GreenDao中Dao對(duì)象其他API的介紹
-
增加單個(gè)數(shù)據(jù)
-
getShopDao().insert(shop);
-
getShopDao().insertOrReplace(shop);
-
-
增加多個(gè)數(shù)據(jù)
-
getShopDao().insertInTx(shopList);
-
getShopDao().insertOrReplaceInTx(shopList);
-
-
查詢?nèi)?/p>
-
List< Shop> list = getShopDao().loadAll();
-
List< Shop> list = getShopDao().queryBuilder().list();
-
-
查詢附加單個(gè)條件
-
.where()
-
.whereOr()
-
-
查詢附加多個(gè)條件
-
.where(, , ,)
-
.whereOr(, , ,)
-
-
查詢附加排序
-
.orderDesc()
-
.orderAsc()
-
-
查詢限制當(dāng)頁(yè)個(gè)數(shù)
-
.limit()
-
-
查詢總個(gè)數(shù)
-
.count()
-
-
修改單個(gè)數(shù)據(jù)
-
getShopDao().update(shop);
-
-
修改多個(gè)數(shù)據(jù)
-
getShopDao().updateInTx(shopList);
-
-
刪除單個(gè)數(shù)據(jù)
-
getTABUserDao().delete(user);
-
-
刪除多個(gè)數(shù)據(jù)
-
getUserDao().deleteInTx(userList);
-
-
刪除數(shù)據(jù)ByKey
-
getTABUserDao().deleteByKey();
-
當(dāng)然,看到其他博客的方法,也可以把對(duì)greenDAO的調(diào)用封裝成為一個(gè)單例模式,方便調(diào)用。
ublic class GreenDaoManager {private DaoMaster mDaoMaster;private DaoSession mDaoSession;private static GreenDaoManager mInstance; //單例private GreenDaoManager(){if (mInstance == null) {DaoMaster.DevOpenHelper devOpenHelper = newDaoMaster.DevOpenHelper(MyApplication.getContext(), "user1-db", null);//此處為自己需要處理的表mDaoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());mDaoSession = mDaoMaster.newSession();}}public static GreenDaoManager getInstance() {if (mInstance == null) {synchronized (GreenDaoManager.class) {//保證異步處理安全操作if (mInstance == null) {mInstance = new GreenDaoManager();}}}return mInstance;}public DaoMaster getMaster() {return mDaoMaster;}public DaoSession getSession() {return mDaoSession;}public DaoSession getNewSession() {mDaoSession = mDaoMaster.newSession();return mDaoSession;} }在Application中配置
下面為一些常用的注解使用方式:
@Entitypublic?class?User {????@Id(autoincrement =?true)????private?Long id;??????@Property(nameInDb =?"USERNAME")????private?String name;??????@NotNull????private?int?repos;??????@Transient????private?int?tempUsageCount;??????...}@Entity?用于標(biāo)識(shí)這是一個(gè)需要Greendao幫我們生成代碼的bean
@Id?標(biāo)明主鍵,括號(hào)里可以指定是否自增
@Property?用于設(shè)置屬性在數(shù)據(jù)庫(kù)中的列名(默認(rèn)不寫就是保持一致)
@NotNull?非空
@Transient?標(biāo)識(shí)這個(gè)字段是自定義的不會(huì)創(chuàng)建到數(shù)據(jù)庫(kù)表里
@Unique?添加唯一約束關(guān)系注解:
@Entitypublic?class?Order {????@Id?private?Long id;??????private?long?customerId;??????@ToOne(joinProperty =?"customerId")????private?Customer customer;}??@Entitypublic?class?Customer {????@Id?private?Long id;}@ToOne?是將自己的一個(gè)屬性與另一個(gè)表建立關(guān)聯(lián)@Entitypublic?class?User {????@Id?private?Long id;??????@ToMany(referencedJoinProperty =?"ownerId")????private?List<Site> ownedSites;}??@Entitypublic?class?Site {????@Id?private?Long id;????private?long?ownerId;}
// ----------------------------@Entitypublic?class?User {????@Id?private?Long id;????@Unique?private?String authorTag;??????@ToMany(joinProperties = {????????????@JoinProperty(name =?"authorTag", referencedName =?"ownerTag")????})????private?List<Site> ownedSites;}??@Entitypublic?class?Site {????@Id?private?Long id;????@NotNull?private?String ownerTag;}// ----------------------------
@ToMany的屬性referencedJoinProperty,類似于外鍵約束。
@JoinProperty?對(duì)于更復(fù)雜的關(guān)系,可以使用這個(gè)注解標(biāo)明目標(biāo)屬性的源屬性。
總結(jié)
以上是生活随笔為你收集整理的GreenDao3.2的基本使用方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。