Android開發資料庫之第三方ORM架構(GreenDao),ormgreendao

來源:互聯網
上載者:User

Android開發資料庫之第三方ORM架構(GreenDao),ormgreendao

     移動APP追求追求功能實現的同時,使用者體驗非常重要。開始APP的同時,要時刻的切換開發人員的角色,如你開發的時候,是

站在APP的開發角色,處於生產者的位置;當你測試的時候,你應該把自己放在使用者的角色上去考慮所做的APP了。舉一個很簡單的

例子,就像我們天天使用手機上的新聞、社交動向更新等,當你沒有網路的時候,也還有資料的存在提供使用者瀏覽,而不是一篇”白

色“的,如同電腦死機一般。這就是移動APP在開發的時候,提供了最後一次網路狀態下的資料緩衝,提到資料緩衝,可想而知有內

存緩衝、硬體緩衝之分。在這我主要講述的是一個硬體緩衝-----Android開發資料庫之第三方ORM架構(GreenDao)。

     開發了那麼久的移動APP,最近工作量比較小,閑著沒事在對開發項目的效能進行最佳化。由於項目裡涉及了大量的緩衝處理和數

據庫運用,需要對資料庫進行頻繁的讀寫、查詢等操作。因此首先想到了對整個項目的資料庫架構進行最佳化。原先使用android本身

內建的sqllite,也就是用的最基本的SQLiteOpenHelper方法,這種方法對自己來說比較方便易懂。但是在使用過程中感覺很繁瑣,

從建表到對錶的增刪改查等操作,如果表對象的屬性很多,就需要使用大量的代碼來執行建表、插入等。在代碼執行中還需要對數

據庫和遊標的進行及時關閉(開啟使用,用完關閉),而且還需要部分sql語言,這在開發中產生bug進行調試時尤其不方便。目前

android經常用的orm架構主要有greenDAO、OrmLite、AndrORM。 綜合了網上的各種評價,greenDAO的運行效率最高,記憶體消耗最

少,效能最佳。因此決定採用greenDAO架構,對項目的orm架構進行改進。

       何以體現greenDAO的優勢呢?下面 greenDAO與ORMLite效能對比:

            

       經過幾天的修改,終於將項目裡的資料庫相關的都最佳化完了。在這過程中,發現greenDAO的效能確實不錯,而且使用相當方便,不再需要涉及到任何的sql語言,可以直接通過對象類進行建表、增刪改查等,尤其是api介面又方便易懂。在摸索學習中發現國內相關學習資料實在實在是太少,遂決定在此記錄下自己對使用這個orm架構的一些心得和方法總結。

一、greenDAO架構相關資源

       首先greenDAO作為第三方的資料庫ORM架構,那必定有它的相關網站等資源。

       1、greenDAO官網:http://greendao-orm.com/    
       2、項目:https://github.com/greenrobot/greenDAO(或者官網)
greenDAO是一個可以協助Android開發人員快速將Java對象映射到SQLite資料庫的表單中的ORM解決方案,通過使用一個簡單的物件導向API,開發人員可以對Java對象進行儲存、更新、刪除和查詢。
greenDAO的主要設計目標:
*最大效能(最快的Android ORM)
*便於使用API
*高度最佳化
*最小記憶體消耗


二、開發使用步驟(重點)

        1、下載greenDAO架構資源後,解壓分析官方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:其他測試相關的工程。

        2、DAO類構造
首先需要建立一個java工程來產生DAO類檔案,該工程需要匯入greendao-generator.jar和freemarker.jar檔案到項目中。

                 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 key<a href="http://www.it165.net/edu/ebg/" target="_blank" class="keylink">word</a>
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檔案)。

                運行後出現以下的提示說明DAO檔案自動產生成功了,重新整理一下DaoExample項目即可看到。

                                

             運行後可以看到,DaoExample項目src-gen下面自動產生了8個檔案,3個實體物件,3個dao,1個DaoMaster,1個DaoSession.


       3、建立表
建立一個實體類
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時,一個實體類只能對應一個表,目前沒法做到一個表對應多個實體類,或者多個表共用一種物件類型。後續的升級也不會針對這一點進行擴充。
 

4、表的增刪改查
增刪改查相當方便,完全的物件導向,不需要涉及到任何的sql語言。
          查詢
範例1:查詢某個表是否包含某個id:
public boolean isSaved(int ID)
{
QueryBuilder<SaveList> qb = saveListDao.queryBuilder();
qb.where(Properties.Id.eq(ID));
qb.buildCount().count();
return qb.buildCount().count() > 0 ? true : false;
}
範例2:擷取整個表的資料集合,一句代碼就搞定!
public List<PhotoGalleryDB> getPhotoGallery()
{
   return photoGalleryDao.loadAll();// 擷取圖片相簿
}
範例3:通過一個欄位值尋找對應的另一個欄位值(為簡便直接使用下面方法,也許有更簡單的方法,尚未嘗試)
/** 通過圖片id尋找其目錄id */
public int getTypeId(int picId)
{
QueryBuilder<PhotoGalleryDB> qb = photoGalleryDao.queryBuilder();
qb.where(Properties.Id.eq(picId));
if (qb.list().size() > 0)
{
return qb.list().get(0).getTypeId();
}
else
{
return -1;
}
}
範例4:尋找所有第一姓名是“Joe”並且以lastname排序。
List joes = userDao.queryBuilder()
.where(Properties.FirstName.eq("Joe"))
.orderAsc(Properties.LastName)
.list();
範例5:多重條件查詢
(1)擷取id為cityId並且infotype為HBContant.CITYINFO_SL的資料集合:
public List<CityInfoDB> getSupportingList(int cityId)
{
QueryBuilder<CityInfoDB> qb = cityInfoDao.queryBuilder();
qb.where(qb.and(Properties.CityId.eq(cityId),Properties.InfoType.eq(HBContant.CITYINFO_SL)));
qb.orderAsc(Properties.Id);// 排序依據
return qb.list();
}
(2)擷取firstname為“Joe”並且出生於1970年10月以後的所有user集合:
QueryBuilder qb = userDao.queryBuilder();
qb.where(Properties.FirstName.eq("Joe"),
qb.or(Properties.YearOfBirth.gt(1970),
qb.and(Properties.YearOfBirth.eq(1970), Properties.MonthOfBirth.ge(10))));
List youngJoes = qb.list();
範例6:擷取某列對象
picJsonDao.loadByRowId(picId);

5.增添/插入、修改
插入資料更加簡單,也是只要一句代碼便能搞定!

                public void addToPhotoTable(Photo p)
{
photoDao.insert(p);
}
插入時需要new一個新的對象,範例如下:
DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "notes-db", null);
db = helper.getWritableDatabase();
daoMaster = new DaoMaster(db);
daoSession = daoMaster.newSession();
noteDao = daoSession.getNoteDao();
Note note = new Note(null, noteText, comment, new Date());
noteDao.insert(note);
修改更新:
photoDao.insertOrReplace(photo);
photoDao.insertInTx(photo);

6.刪除:
           (1)清空表格資料
           /** 清空相簿圖片列表的資料 */
           public void clearPhoto()
           {
           photoDao.deleteAll();
           }
(2)刪除某個對象
 {
       QueryBuilder<DBCityInfo> qb = cityInfoDao.queryBuilder();
       DeleteQuery<DBCityInfo> bd = qb.where(Properties.CityId.eq(cityId)).buildDelete();
       bd.executeDeleteWithoutDetachingEntities();
}
由上可見,使用greenDAO進行資料庫的增刪改查時及其方便,而且效能極佳。


 三、常用方法筆記
1.在Application實現得到DaoMaster和DaoSession的方法:
private static DaoMaster daoMaster;
private static DaoSession daoSession;
/**
* 取得DaoMaster
*
* @param context
* @return
*/
public static DaoMaster getDaoMaster(Context context)
{
if (daoMaster == null)
{
OpenHelper helper = new DaoMaster.DevOpenHelper(context, HBContant.DATABASE_NAME, null);
daoMaster = new DaoMaster(helper.getWritableDatabase());
}
return daoMaster;
}
/**
* 取得DaoSession
*
* @param context
* @return
*/
public static DaoSession getDaoSession(Context context)
{
if (daoSession == null)
{
if (daoMaster == null)
{
daoMaster = getDaoMaster(context);
}
daoSession = daoMaster.newSession();
}
return daoSession;
}
2.增刪改查工具類:
public class DBHelper
{
private static Context mContext;
private static DBHelper instance;
 
private CityInfoDBDao cityInfoDao;
 
private DBHelper()
{
}
 
public static DBHelper getInstance(Context context)
{
if (instance == null)
{
instance = new DBHelper();
if (mContext == null)
{
mContext = context;
}
 
// 資料庫物件
DaoSession daoSession = HBApplication.getDaoSession(mContext);
instance.cityInfoDao = daoSession.getCityInfoDBDao();
}
return instance;
}
 
/** 添加資料 */
public void addToCityInfoTable(CityInfo item)
{
cityInfoDao.insert(item);
}
 
/** 查詢 */
public List<EstateLoveListJson> getCityInfoList()
{
QueryBuilder<CityInfo> qb = cityInfoDao.queryBuilder();
return qb.list();
}
 
/** 查詢 */
public List<CityInfo> getCityInfo()
{
return cityInfoDao.loadAll();// 尋找圖片相簿
}
 
/** 查詢 */
public boolean isSaved(int Id)
{
QueryBuilder<CityInfo> qb = cityInfoDao.queryBuilder();
qb.where(Properties.Id.eq(Id));
qb.buildCount().count();
return qb.buildCount().count() > 0 ? true : false;// 尋找收藏表
}
 
/** 刪除 */
public void deleteCityInfoList(int Id)
{
QueryBuilder<CityInfo> qb = cityInfoDao.queryBuilder();
DeleteQuery<CityInfo> bd = qb.where(Properties.Id.eq(Id)).buildDelete();
bd.executeDeleteWithoutDetachingEntities();
}
 
/** 刪除 */
public void clearCityInfo()
{
cityInfoDao.deleteAll();
}
 
/** 通過城市id尋找其類型id */
public int getTypeId(int cityId)
{
QueryBuilder<CityInfo> qb = cityInfoDao.queryBuilder();
qb.where(Properties.Id.eq(cityId));
if (qb.list().size() > 0)
{
return qb.list().get(0).getTypeId();
}
else
{
return 0;
}
}
 
/** 多重查詢 */
public List<CityInfo> getIphRegionList(int cityId)
{
QueryBuilder<CityInfoDB> qb = cityInfoDao.queryBuilder();
qb.where(qb.and(Properties.CityId.eq(cityId), Properties.InfoType.eq(HBContant.CITYINFO_IR)));
qb.orderAsc(Properties.Id);// 排序依據
return qb.list();
}
}
       另外,還有多表關聯、惰性載入等功能,待後續研究。
參考資料:
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



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.