版權聲明:本文為部落客原創文章,轉載請标明出處。 https://blog.csdn.net/chaoyu168/article/details/80228390
一、簡介
greenDAO是一個對象關系映射(ORM)的架構,能夠提供一個接口通過操作對象的方式去操作關系型資料庫,它能夠讓你操作資料庫時更簡單、更友善。如下圖所示:
Github位址:
https://github.com/greenrobot/greenDAOGreenDao 優點:
1.性能高,号稱Android最快的關系型資料庫
2.記憶體占用小
3.庫檔案比較小,小于100K,編譯時間低,而且可以避免65K方法限制
4.支援資料庫加密 greendao支援SQLCipher進行資料庫加密 有關SQLCipher可以參考這篇部落格
Android資料存儲之Sqlite采用SQLCipher資料庫加密實戰5.簡潔易用的API
二、配置
1、需要在工程(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'
}
}
2、在項目(Module)的build.gradle中添加依賴
apply plugin: 'com.android.application'
//使用greendao
apply plugin: 'org.greenrobot.greendao'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "com.handsome.didi"
minSdkVersion 14
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
//greendao配置
greendao {
//版本号,更新時可配置
schemaVersion 1
}
buildTypes {
release {
minifyEnabled false
proguardFiles 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'
}
三、使用
1、建立Bean對象(表名和字段名)
GreenDao需要建立Bean對象之後,該Bean對象就是表名,而它的屬性值就是字段名,其實作是通過注釋的方式來實作的,下面是購物車的Bean對象(每個Bean對象對應一張表)
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Generated;
/**
* app實體類
*/
@Entity
public class app {
//不能用int
@Id(autoincrement = true)
private Long id;
private String packageName;
private String label;
private String versionName;
private int versionCode;
private String sourceDir;
private String dataDir;
private boolean system;
private boolean installed;
@Generated(hash = 1362904721)
public app(Long id, String packageName, String label, String versionName,
int versionCode, String sourceDir, String dataDir, boolean system,
boolean installed) {
this.id = id;
this.packageName = packageName;
this.label = label;
this.versionName = versionName;
this.versionCode = versionCode;
this.sourceDir = sourceDir;
this.dataDir = dataDir;
this.system = system;
this.installed = installed;
}
@Generated(hash = 1515546537)
public app() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getPackageName() {
return this.packageName;
}
public void setPackageName(String packageName) {
this.packageName = packageName;
}
public String getLabel() {
return this.label;
}
public void setLabel(String label) {
this.label = label;
}
public String getVersionName() {
return this.versionName;
}
public void setVersionName(String versionName) {
this.versionName = versionName;
}
public int getVersionCode() {
return this.versionCode;
}
public void setVersionCode(int versionCode) {
this.versionCode = versionCode;
}
public String getSourceDir() {
return this.sourceDir;
}
public void setSourceDir(String sourceDir) {
this.sourceDir = sourceDir;
}
public String getDataDir() {
return this.dataDir;
}
public void setDataDir(String dataDir) {
this.dataDir = dataDir;
}
public boolean getSystem() {
return this.system;
}
public void setSystem(boolean system) {
this.system = system;
}
public boolean getInstalled() {
return this.installed;
}
public void setInstalled(boolean installed) {
this.installed = installed;
}
}
這裡需要注意的是,建立完成之後,需要build gradle來完成我們的代碼自動生成。自動生成的代碼有
- Bean實體的構造方法和get、set方法
- DaoMaster、DaoSession、DAOS類
這裡對Bean對象的注釋進行解釋
- @Entity:告訴GreenDao該對象為實體,隻有被@Entity注釋的Bean類才能被dao類操作
- @Id:對象的Id,使用Long類型作為EntityId,否則會報錯。(autoincrement = true)表示主鍵會自增,如果false就會使用舊值
- @Property:可以自定義字段名,注意外鍵不能使用該屬性
- @NotNull:屬性不能為空
- @Transient:使用該注釋的屬性不會被存入資料庫的字段中
- @Unique:該屬性值必須在資料庫中是唯一值
- @Generated:編譯後自動生成的構造函數、方法等的注釋,提示構造函數、方法等不能被修改
2、GreenDao資料庫建立
public class MyApplication extends Application {
private static DaoSession daoSession;
@Override
public void onCreate() {
super.onCreate();
//配置資料庫
setupDatabase();
}
/**
* 配置資料庫
*/
private void setupDatabase() {
//建立資料庫app.db"
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "app.db", null);
//擷取可寫資料庫
SQLiteDatabase db = helper.getWritableDatabase();
//擷取資料庫對象
DaoMaster daoMaster = new DaoMaster(db);
//擷取Dao對象管理者
daoSession = daoMaster.newSession();
}
public static DaoSession getDaoInstant() {
return daoSession;
}
}
可以發現,GreenDao已經将我們的資料庫建立縮成幾句話,代碼會自動将Bean對象建立成表,不再是傳統的手寫SQL語句。這裡的資料庫建立隻需要在Application中執行一次即可,這裡對幾個類進行解釋
- DevOpenHelper:建立SQLite資料庫的SQLiteOpenHelper的具體實作
- DaoMaster:GreenDao的頂級對象,作為資料庫對象、用于建立表和删除表
- DaoSession:管理所有的Dao對象,Dao對象中存在着增删改查等API
由于我們已經建立好了DaoSession和Shop的Bean對象,編譯後會自動生成我們的ShopDao對象,可通過DaoSession獲得
AppDao dao = daoSession.getAppDao();
這裡的Dao(Data Access Object)是指資料通路接口,即提供了資料庫操作一些API接口,可通過dao進行增删改查操作
3、資料庫的增删改查
public class utilsDao {
/**
* 添加資料,如果有重複則覆寫
*
* @param shop
*/
public static void insertLove(app shop) {
BaseApplication.getDaoInstant().getShopDao().insertOrReplace(shop);
}
/**
* 删除資料
*
* @param id
*/
public static void deleteLove(long id) {
BaseApplication.getDaoInstant().getShopDao().deleteByKey(id);
}
/**
* 更新資料
*
* @param shop
*/
public static void updateLove(app shop) {
BaseApplication.getDaoInstant().getShopDao().update(shop);
}
/**
* 查詢條件為Label=秒拍 的資料
*
* @return
*/
public static List<app> queryLove() {
return BaseApplication.getAppDao().queryBuilder().where(appDao.Properties.Label.eq("秒拍")).list();
}
/**
* 查詢全部資料
*/
public static List<app> queryAll() {
return BaseApplication.getDaoInstant().getShopDao().loadAll();
}
}
效果很明顯,GreenDao的封裝更加短小精悍,語義明朗,下面對GreenDao中Dao對象其他API的介紹
- 增加單個資料
- getShopDao().insert(shop);
- getShopDao().insertOrReplace(shop);
- 增加多個資料
- getShopDao().insertInTx(shopList);
- getShopDao().insertOrReplaceInTx(shopList);
- 查詢全部
- List< Shop> list = getShopDao().loadAll();
- List< Shop> list = getShopDao().queryBuilder().list();
- 查詢附加單個條件
- .where()
- .whereOr()
- 查詢附加多個條件
- .where(, , ,)
- .whereOr(, , ,)
- 查詢附加排序
- .orderDesc()
- .orderAsc()
- 查詢限制當頁個數
- .limit()
- 查詢總個數
- .count()
- 修改單個資料
- getShopDao().update(shop);
- 修改多個資料
- getShopDao().updateInTx(shopList);
- 删除單個資料
- getTABUserDao().delete(user);
- 删除多個資料
- getUserDao().deleteInTx(userList);
- 删除資料ByKey
- getTABUserDao().deleteByKey();
自己封裝的工具類:
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.xiaobai.cloneapp.domain.DaoMaster;
import com.xiaobai.cloneapp.domain.DaoSession;
import com.xiaobai.cloneapp.domain.dirinfo;
import com.xiaobai.cloneapp.domain.dirinfoDao;
import org.greenrobot.greendao.query.QueryBuilder;
import java.util.List;
/**
* 資料庫管理
*/
public class DBManager {
private final static String dbName = "appinfo.db";
private static DBManager mInstance;
private DaoMaster.DevOpenHelper openHelper;
private Context context;
private DaoSession sDaoSession;
private static DaoMaster sDaoMaster;
public DBManager(Context context) {
this.context = context;
openHelper = new DaoMaster.DevOpenHelper(context, dbName, null);
}
/**
* 擷取單例引用
*
* @param context
* @return
*/
public static DBManager getInstance(Context context) {
if (mInstance == null) {
synchronized (DBManager.class) {
if (mInstance == null) {
mInstance = new DBManager(context);
}
}
}
return mInstance;
}
/**
* 判斷是否有存在資料庫,如果沒有則建立
* @return
*/
public DaoMaster getDaoMaster(String DBName){
if(sDaoMaster == null) {
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, DBName, null);
sDaoMaster = new DaoMaster(helper.getWritableDatabase());
}
return sDaoMaster;
}
/**
* 擷取可寫資料庫
*/
private SQLiteDatabase getWritableDatabase() {
if (openHelper == null) {
openHelper = new DaoMaster.DevOpenHelper(context, dbName, null);
}
SQLiteDatabase db = openHelper.getWritableDatabase();
return db;
}
/**
* 擷取可讀資料庫
*/
private SQLiteDatabase getReadableDatabase() {
if (openHelper == null) {
openHelper = new DaoMaster.DevOpenHelper(context, dbName, null);
}
SQLiteDatabase db = openHelper.getReadableDatabase();
return db;
}
/**
* 插入dirinfo一條記錄
*
* @param
*/
public void insertDir(dirinfo dir) {
DaoMaster daoMaster = new DaoMaster(getWritableDatabase());
sDaoSession = daoMaster.newSession();
dirinfoDao dirDao = sDaoSession.getDirinfoDao();
dirDao.insertOrReplace(dir);
}
/**
* 查詢使用者清單
*/
/**
* 查詢使用者清單
*/
public List<dirinfo> queryDirList() {
DaoMaster daoMaster = new DaoMaster(getReadableDatabase());
DaoSession daoSession = daoMaster.newSession();
dirinfoDao dirDao = daoSession.getDirinfoDao();
QueryBuilder<dirinfo> qb = dirDao.queryBuilder();
List<dirinfo> list = qb.list();
return list;
}
public List<dirinfo> queryDirList(String DIRECTION) {
DaoMaster daoMaster = new DaoMaster(getReadableDatabase());
DaoSession daoSession = daoMaster.newSession();
dirinfoDao dirDao = daoSession.getDirinfoDao();
QueryBuilder<dirinfo> qb = dirDao.queryBuilder();
qb.where(dirinfoDao.Properties.Direction.gt(DIRECTION)).orderAsc(dirinfoDao.Properties.Direction);
List<dirinfo> list = qb.list();
return list;
}
/**
* 更新一條記錄
*
* @param dir
*/
public void updatedir(dirinfo dir) {
DaoMaster daoMaster = new DaoMaster(getWritableDatabase());
DaoSession daoSession = daoMaster.newSession();
dirinfoDao dirDao = daoSession.getDirinfoDao();
dirDao.update(dir);
}
/**
* 删除一條記錄
*
* @param dir
*/
public void deleteUser(dirinfo dir) {
DaoMaster daoMaster = new DaoMaster(getWritableDatabase());
DaoSession daoSession = daoMaster.newSession();
dirinfoDao dirDao = daoSession.getDirinfoDao();
dirDao.delete(dir);
}
/**
* 删除所有資料
*
* @param
*/
public void deleteAllDir() {
DaoMaster daoMaster = new DaoMaster(getWritableDatabase());
DaoSession daoSession = daoMaster.newSession();
dirinfoDao dirDao = daoSession.getDirinfoDao();
dirDao.deleteAll();
}
/**
* 關閉所有的操作,資料庫開啟後,使用完畢要關閉
*/
public void closeConnection(){
closeHelper();
closeDaoSession();
}
private void closeHelper(){
if(openHelper != null){
openHelper.close();
openHelper = null;
}
}
private void closeDaoSession(){
if(sDaoSession != null){
sDaoSession.clear();
sDaoSession = null;
}
}
}