首頁
andorid 數據庫框架
正文
GreeDAO 使用
最近在對開發項目的性能進行優化。由於項目裏涉及了大量的緩存處理和數據庫運用,需要對數據庫進行頻繁的讀寫、查詢等操作。因此首先想到了對整個項目的數據庫框架進行優化。原先使用android本身內置的sqllite,也就是用的最基本的SQLiteOpenHelper方法,這種方法對自己來說比較方便易懂。但是在使用過程中感覺很繁瑣,從建表到對錶的增刪改查等操作,如果表對象的屬性很多,就需要使用大量的代碼來執行建表、插入等。在代碼執行中還需要對數據庫和遊標的進行及時關閉(開啓使用,用完關閉),而且還需要部分sql語言,這在開發中產生bug進行調試時尤其不方便。 目前android經常用的orm框架主要有greenDAO、OrmLite、AndrORM。 綜合了網上的各種評價,greenDAO的運行效率最高,內存消耗最少,性能最佳。因此決定採用greenDAO框架,對項目的orm框架進行改進。 greenDAO與ORMLite性能對比經過兩天的修改,終於將項目裏的數據庫相關的都優化完了。在這過程中,發現greenDAO的性能確實不錯,而且使用相當方便,不再需要涉及到任何的sql語言,可以直接通過對象類進行建表、增刪改查等,尤其是api接口又方便易懂。在摸索學習中發現國內相關學習資料實在實在是太少,遂決定在此記錄下自己對使用這個orm框架的一些心得和方法總結。 一、greenDAO相關 1.greenDAO官網:http://greendao-orm.com/ 2.項目下載地址:https://github.com/greenrobot/greenDAO(或者官網) greenDAO是一個可以幫助 Android 開發者快速將Java對象映射到SQLite數據庫的表單中的ORM解決方案,通過使用一個簡單的面向對象API,開發者可以對Java對象進行存儲、更新、刪除和查詢。 greenDAO的主要設計目標: *最大性能(最快的 Android ORM) *易於使用API *高度優化 *最小內存消耗 二、使用步驟 官方Demo裏共有六個工程目錄,分別爲: (1).DaoCore:庫目錄,即jar文件greendao-1.3.0-beta-1.jar的代碼; (2).DaoExample:android範例工程; (3).DaoExampleGenerator:DaoExample工程的DAO類構造器,java工程; (4).DaoGenerator:DAO類構造器,java工程; (5).DaoTest、PerformanceTestOrmLite:其他測試相關的工程。 (一)DAO類構造 首先需要新建一個java工程來生成DAO類文件,該工程需要導入greendao-generator.jar和freemarker.jar文件到項目中。
package de.greenrobot.daogenerator.gentest;
import de.greenrobot.daogenerator.DaoGenerator;
import de.greenrobot.daogenerator.Entity;
import de.greenrobot.daogenerator.Property;
import de.greenrobot.daogenerator.Schema;
import de.greenrobot.daogenerator.ToMany;
/** * Generates entities and DAOs for the example project DaoExample. * * Run it as a Java application (not Android). * * @author Markus */
public class ExampleDaoGenerator
{ public static void main(String[] args) throws Exception { Schema schema = new Schema(3, "de.greenrobot.daoexample"); addNote(schema); addCustomerOrder(schema); new DaoGenerator().generateAll(schema, "../DaoExample/src-gen");
} private static void addNote(Schema schema) { Entity note = schema.addEntity("Note"); note.addIdProperty(); note.addStringProperty("text").notNull(); note.addStringProperty("comment"); note.addDateProperty("date");
} private static void addCustomerOrder(Schema schema) { Entity customer = schema.addEntity("Customer"); customer.addIdProperty(); customer.addStringProperty("name").notNull(); Entity order = schema.addEntity("Order");
order.setTableName("ORDERS"); // "ORDER" is a reserved keyword order.addIdProperty(); Property orderDate = order.addDateProperty("date").getProperty(); Property customerId = order.addLongProperty("customerId").notNull().getProperty();
order.addToOne(customer, customerId); ToMany customerToOrders = customer.addToMany(order, customerId); customerToOrders.setName("orders"); customerToOrders.orderAsc(orderDate); }
}
複製代碼
在main方法中,
Schema schema = new Schema(3, "de.greenrobot.daoexample");
複製代碼
該方法第一個參數用來更新數據庫版本號,第二個參數爲要生成的DAO類所在包路徑。 然後進行建表和設置要生成DAO文件的目標工程的項目路徑。
addNote(schema);
addCustomerOrder(schema);
new DaoGenerator().generateAll(schema, "../DaoExample/src-gen");
複製代碼
其中src-gen這個目錄名需要在運行前手動創建,否則會報錯。 如果運行後出現以下錯誤,則導入DaoGenerator項目的dao.ftl文件即可(或者直接使用DaoGenerator來生成DAO文件)。
Exception in thread "main" java.io.FileNotFoundException: Template "dao.ftl" not found. at freemarker.template.Configuration.getTemplate(Configuration.java:742) at freemarker.template.Configuration.getTemplate(Configuration.java:665) at de.greenrobot.daogenerator.DaoGenerator.(DaoGenerator.java:68)
at de.greenrobot.daogenerator.gentest.ExampleDaoGenerator.main(ExampleDaoGenerator.java:41)
複製代碼
運行後出現以下的提示說明DAO文件自動生成成功了,刷新一下DaoExample項目即可看到。
greenDAO Generator
Copyright 2011-2013 Markus Junginger, greenrobot.de. Licensed under GPL V3.
This program comes with ABSOLUTELY NO WARRANTY
Processing schema version 3...
Written F:Android_Exwork_10DaoExamplesrc-gendegreenrobotdaoexampleNoteDao.java
Written F:Android_Exwork_10DaoExamplesrc-gendegreenrobotdaoexampleNote.java
Written F:Android_Exwork_10DaoExamplesrc-gendegreenrobotdaoexampleCustomerDao.java
Written F:Android_Exwork_10DaoExamplesrc-gendegreenrobotdaoexampleCustomer.java
Written F:Android_Exwork_10DaoExamplesrc-gendegreenrobotdaoexampleOrderDao.java
Written F:Android_Exwork_10DaoExamplesrc-gendegreenrobotdaoexampleOrder.java
Written F:Android_Exwork_10DaoExamplesrc-gendegreenrobotdaoexampleDaoMaster.java
Written F:Android_Exwork_10DaoExamplesrc-gendegreenrobotdaoexampleDaoSession.java
Processed 3 entities in 204ms
複製代碼
運行後可以看到,DaoExample項目src-gen下面自動生成了8個文件,3個實體對象,3個dao,1個DaoMaster,1個DaoSession. (二)創建表 1.創建一個實體類
Entity note = schema.addEntity("Note");
複製代碼
默認表名就是類名,也可以自定義表名
dao.setTableName("NoteList");
複製代碼
greenDAO會自動根據實體類屬性創建表字段,並賦予默認值。例如在數據庫方面的表名和列名都來源於實體類名和屬性名。默認的數據庫名稱是大寫使用下劃線分隔單詞,而不是在Java中使用的駝峯式大小寫風格。例如,一個名爲“CREATIONDATE”屬性將成爲一個數據庫列“CREATION_DATE”。 設置一個自增長ID列爲主鍵:
dao.addIdProperty().primaryKey().autoincrement();
複製代碼
設置其他各種類型的屬性:
dao.addIntProperty("cityId");
dao.addStringProperty("infoType").notNull();//非null字段
dao.addDoubleProperty("Id");
複製代碼
在生成的實體類中,int類型爲自動轉爲long類型。 如果在編譯過程中出現以下錯誤,那麼有可能是主鍵的類型錯誤所致:
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
複製代碼
在使用greenDAO時,一個實體類只能對應一個表,目前沒法做到一個表對應多個實體類,或者多個表共用一種對象類型。後續的升級也不會針對這一點進行擴展。 (二)表的增刪改查 增刪改查相當方便,完全的面向對象,不需要涉及到任何的sql語言。 1.查詢 範例1:查詢某個表是否包含某個id:
Schema schema = new Schema(3, "de.greenrobot.daoexample");0
複製代碼
範例2:獲取整個表的數據集合,一句代碼就搞定!
Schema schema = new Schema(3, "de.greenrobot.daoexample");1
複製代碼
範例3:通過一個字段值查找對應的另一個字段值(爲簡便直接使用下面方法,也許有更簡單的方法,尚未嘗試)
Schema schema = new Schema(3, "de.greenrobot.daoexample");2
複製代碼
範例4:查找所有第一姓名是“Joe”並且以lastname排序。
Schema schema = new Schema(3, "de.greenrobot.daoexample");3
複製代碼
範例5:多重條件查詢 (1)獲取id爲cityId並且infotype爲HBContant.CITYINFO_SL的數據集合:
Schema schema = new Schema(3, "de.greenrobot.daoexample");4
複製代碼
(2)獲取firstname爲“Joe”並且出生於1970年10月以後的所有user集合:
Schema schema = new Schema(3, "de.greenrobot.daoexample");5
複製代碼
範例6:獲取某列對象
Schema schema = new Schema(3, "de.greenrobot.daoexample");6
複製代碼
2.增添/插入、修改 插入數據更加簡單,也是隻要一句代碼便能搞定!
Schema schema = new Schema(3, "de.greenrobot.daoexample");7
複製代碼
插入時需要new一個新的對象,範例如下:
Schema schema = new Schema(3, "de.greenrobot.daoexample");8
複製代碼
修改更新:
Schema schema = new Schema(3, "de.greenrobot.daoexample");9
複製代碼
3.刪除: (1)清空表格數據
addNote(schema);
addCustomerOrder(schema);
new DaoGenerator().generateAll(schema, "../DaoExample/src-gen");0
複製代碼
(2)刪除某個對象
addNote(schema);
addCustomerOrder(schema);
new DaoGenerator().generateAll(schema, "../DaoExample/src-gen");1
複製代碼
參考:https://github.com/greenrobot/greenDAO/issues/34 由上可見,使用greenDAO進行數據庫的增刪改查時及其方便,而且性能極佳。 (三)常用方法筆記 1.在Application實現得到DaoMaster和DaoSession的方法:
addNote(schema);
addCustomerOrder(schema);
new DaoGenerator().generateAll(schema, "../DaoExample/src-gen");2
複製代碼
2.增刪改查工具類:
addNote(schema);
addCustomerOrder(schema);
new DaoGenerator().generateAll(schema, "../DaoExample/src-gen");3
複製代碼
另外,還有多表關聯、惰性加載等功能,待後續研究。 參考資料: 1.https://github.com/greenrobot/greenDAO 2.http://greendao-orm.com/documentation/how-to-get-started/ 3.http://blog.csdn.net/krislight/article/details/9391455