效果圖:
點此進入目錄:[乾貨] 十天 教你從創意到上線APP
一、什麼是greenDao?
greenDao是一個將對象映射到SQLite數據庫中的輕量且快速的ORM解決方案。
二、爲什麼選用greenDAO ?
- greenDAO 可以將我們數據庫的中數據轉換爲相應的對象,這樣可以省去我們自己去轉換對象的時間。
- 和同類型的庫相比,性能是最好的。(與OrmLite、ActiveOrm、LitePal等數據庫相比,單位時間內可以插入、更新和查詢更多的數據,而且提供了大量的靈活通用接口,對比可見下圖。)
- greenDAO 也是當前 Android 開發中比較流行的庫,當前的 github 星星數爲 7369。
- 使用 SQL 語句進行查詢容易出錯,而且錯誤比較難以發現,使用 greenDAO 的話可以在編譯階段就發現錯誤。
- 還有就是代碼比較簡單明瞭,程序員都想用最少的代碼,做最多的事。
- 輕量級,整個庫大小小於 150 k。
三、GreenDao 3.0的使用
當前的 greenDAO 要求 gradle 的版本至少是 3.3,那我們採用3.3來實現。其中GreenDao 3.1採用註解的方式來定義實體類,通過gradle插件生成相應的代碼。
1、在Android Studio中導入相關的包
compile 'org.greenrobot:greendao:3.1.0'
compile 'org.greenrobot:greendao-generator:3.1.0'
2、在build.gradle中進行配置
buildscript {
repositories {
jcenter()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.3.3'
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
classpath 'org.greenrobot:greendao-gradle-plugin:3.1.0'
}
}
注:在gradle的根模塊中加入上述代碼。
3、自定義路徑
greendao {
schemaVersion 1
daoPackage 'com.wgh.willflowaicollection.greendao'
targetGenDir 'src/main/java'
}
屬性介紹:
- schemaVersion : 指定數據庫schema版本號,遷移等操作會用到;
- daoPackage : dao的包名,包名默認是entity所在的包;
- targetGenDir : 生成數據庫文件的目錄;
在gradle的根模塊中加入上述代碼,就完成了我們的基本配置了。
4、創建一個Category的實體類
/**
* Created by : WGH.
*/
@Entity
public class Category implements Serializable {
private static final long serialVersionUID = 7247714666080613254L;
@Id(autoincrement = true)
private Long id;
private int grade;
private String name;
private String selfKey;
@Convert(columnType = String.class, converter = ListConverter.class)
private ArrayList<String> nextNames = new ArrayList<>();
@Convert(columnType = String.class, converter = ListConverter.class)
private ArrayList<String> contentUrls = new ArrayList<>();
@Convert(columnType = String.class, converter = ListConverter.class)
private ArrayList<String> contentTitles = new ArrayList<>();
@Convert(columnType = String.class, converter = ListConverter.class)
private ArrayList<String> nextKeys = new ArrayList<>();
public Category() {
}
@Generated(hash = 182005897)
public Category(Long id, int grade, String name, String selfKey, ArrayList<String> nextNames, ArrayList<String> contentUrls, ArrayList<String> contentTitles, ArrayList<String> nextKeys) {
this.id = id;
this.grade = grade;
this.name = name;
this.selfKey = selfKey;
this.nextNames = nextNames;
this.contentUrls = contentUrls;
this.contentTitles = contentTitles;
this.nextKeys = nextKeys;
}
public Category(int grade, String name) {
this.grade = grade;
this.name = name;
}
}
5、構造數據轉換模板類
/**
* Created by : WGH.
*/
public class ListConverter implements PropertyConverter<ArrayList<String>, String> {
@Override
public ArrayList<String> convertToEntityProperty(String databaseValue) {
ArrayList<String> arrayList;
if (databaseValue == null) {
return null;
} else {
List<String> list = Arrays.asList(databaseValue.split(PreDefine.SplitString));
arrayList = new ArrayList<>(list);
return arrayList;
}
}
@Override
public String convertToDatabaseValue(ArrayList<String> entityProperty) {
if (entityProperty == null) {
return null;
} else {
StringBuilder sb = new StringBuilder();
for (String entity : entityProperty) {
sb.append(entity);
sb.append(PreDefine.SplitString);
}
return sb.toString();
}
}
}
6、編譯工程
編譯項目後Category實體類會自動編譯,然後生成get、set方法並且會在greendao目錄下生成三個文件:
另外的三個是其它數據類構造出來的三個文件,在這裏可以不用理會。
四、greenDao的增刪改查操作
首先在 MyApplication 中進行這樣設置:
/**
* Created by : WGH.
*/
public class MyApplication extends Application{
private static DaoMaster daoMaster;
private static DaoSession daoSession;
@Override
public void onCreate() {
super.onCreate();
}
public static DaoMaster getDaoMaster() {
if (daoMaster == null) {
DaoMaster.OpenHelper helper = new DaoMaster.DevOpenHelper(mMyApplication, PreDefine.DBNAME, null);
daoMaster = new DaoMaster(helper.getReadableDatabase());
}
return daoMaster;
}
public static DaoSession getDaoSession() {
if (daoSession == null) {
if (daoMaster == null) {
daoMaster = getDaoMaster();
}
daoSession = daoMaster.newSession();
}
return daoSession;
}
}
然後在使用greenDao的地方進行這樣的調用:
CategoryDao categoryDao = MyApplication.getDaoSession().getCategoryDao();
這樣就能獲得categoryDao 對象了。
1、增刪改查的簡單實現
- 增
Category categoryNew = new Category();
CategoryDao categoryDao = MyApplication.getDaoSession().getCategoryDao();
categoryDao.insert(categoryNew);
- 刪
public void deleteCategoryFromDB(Category category) {
CategoryDao categoryDao = MyApplication.getDaoSession().getCategoryDao();
Category categoryOld = getCategotyFromDB(category.getKey());
if (categoryOld != null) {
categoryDao.delete(categoryOld);
}
}
- 刪除全部
public void deleteAllCategory() {
CategoryDao categoryDao = MyApplication.getDaoSession().getCategoryDao();
categoryDao.deleteAll();
}
- 改
public void updateCategoryToDB(Category categoryNew) {
CategoryDao categoryDao = MyApplication.getDaoSession().getCategoryDao();
Category categoryOld = getCategotyFromDB(categoryNew.getKey());
categoryNew.setId(categoryOld.getId());
categoryDao.update(categoryNew);
}
- Key值查找
public Category getCategotyFromDB(String key) {
if (TextUtils.isEmpty(key)) {
return null;
}
CategoryDao categoryDao = MyApplication.getDaoSession().getCategoryDao();
QueryBuilder<Category> queryBuilder = categoryDao.queryBuilder().where(CategoryDao.Properties.SelfKey.eq(key));
if (queryBuilder.list().size() > 0) {
return queryBuilder.list().get(0);
} else {
return null;
}
}
- 模糊查詢
public ArrayList<Category> getEligibleCategory(String contentString) {
CategoryDao categoryDao = MyApplication.getDaoSession().getCategoryDao();
QueryBuilder<Category> queryBuilder = categoryDao.queryBuilder().where(CategoryDao.Properties.ContentTitles.like("%" + contentString + "%"));
if (queryBuilder.list().size() > 0) {
return new ArrayList<>(queryBuilder.list());
} else {
return null;
}
}
- 查詢全部
public ArrayList<Category > getAllCategory () {
Category category = MyApplication.getDaoSession().getCategoryDao();
return new ArrayList<>(category .loadAll());
}
- 條件查詢
List<Category > list = categoryDao.queryBuilder()
.offset(1)//偏移量,相當於 SQL 語句中的 skip
.limit(3)//只獲取結果集的前 3 個數據
.orderAsc(categoryDao.Properties.StudentNum)//通過 StudentNum 這個屬性進行正序排序
.where(categoryDao.Properties.Name.eq("zone"))//數據篩選,只獲取 Name = "zone" 的數據。
.build()
.list();
2、greenDao中的註解詳解
(一) @Entity 定義實體
- @nameInDb 在數據庫中的名字,如不寫則爲實體中類名
- @indexes 索引
- @createInDb 是否創建表,默認爲true,false時不創建
- @schema 指定架構名稱爲實體
- @active 無論是更新生成都刷新
(二) @Id
(三) @NotNull 不爲null
(四) @Unique 唯一約束
(五) @ToMany 一對多
(六) @OrderBy 排序
(七) @ToOne 一對一
(八) @Transient 不存儲在數據庫中
(九) @generated 由greendao產生的構造函數或方法
聯繫方式: