Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 資料庫高手秘籍(七)——體驗 LitePal 的查詢藝術

編輯:關於 Android 程式設計

經過前面幾篇的鋪墊,增刪改三種操作我們都已經學完了。現在回頭看,用 LitePal 操作資料庫確實輕我已不少。但資料庫操作中真正最複雜、用法最多的,其實是查詢。LitePal 在這塊提供的 API 相當豐富,設計上也頗具巧思。這篇就專門來拆解查詢操作。

還沒看過前一篇的朋友,建議先參考〈Android 資料庫高手秘籍(六)——LitePal 的修改和刪除操作〉。

一、傳統的查詢方式有多麻煩

最原始的方式是直接寫 SQL,透過 SQLiteDatabase 的 rawQuery():

public Cursor rawQuery(String sql, String[] selectionArgs)

第一個參數是 SQL 字串,第二個是用來替換占位符(?)的字串陣列。回傳一個 Cursor,所有結果都封裝在裡面。

但多數人並不喜歡手寫 SQL,於是 Android 另外提供了封裝好的 query()。它有三個重載版本,參數最少的也有七個:

public Cursor query(String table, String[] columns, String selection,
                    String[] selectionArgs, String groupBy,
                    String having, String orderBy)
  • 第一個參數:表名。
  • 第二個參數:要查詢的欄位,不指定則查全部。
  • 第三、四個參數:約束條件,不指定則查全部列。
  • 第五個參數:group by 的欄位。
  • 第六個參數:對 group by 結果進一步過濾。
  • 第七個參數:排序方式。

想查 news 表的全部資料,得這樣寫:

SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor cursor = db.query(news, null, null, null, null, null, null);

六個用不到的參數,全都得填 null。若加上條件——查詢評論數大於零的新聞:

Cursor cursor = db.query(news, null, "commentcount>?",
                         new String[]{ "0" }, null, null, null);

剩下的參數依舊只能填 null。

更麻煩的是,結果還得自己從 Cursor 逐一取出、再塞進實體類別:

List<News> newsList = new ArrayList<News>();

if (cursor != null && cursor.moveToFirst()) {
    do {
        int id = cursor.getInt(cursor.getColumnIndex("id"));
        String title = cursor.getString(cursor.getColumnIndex("title"));
        String content = cursor.getString(cursor.getColumnIndex("content"));
        Date publishDate = new Date(cursor.getLong(cursor.getColumnIndex("publishdate")));
        int commentCount = cursor.getInt(cursor.getColumnIndex("commentcount"));

        News news = new News();
        news.setId(id);
        news.setTitle(title);
        news.setContent(content);
        news.setPublishDate(publishDate);
        news.setCommentCount(commentCount);
        newsList.add(news);
    } while (cursor.moveToNext());
}

冗長的參數列表加上手工映射,就是傳統查詢的日常。你可能已經習慣了,但習慣是可以改變的。

二、LitePal 的查詢 API

LitePal 做了兩個關鍵改變:用連綴查詢取代冗長參數,以及直接回傳封裝好的物件而非 Cursor。

簡單查詢

查詢 news 表中 id 為 1 的記錄:

News news = DataSupport.find(News.class, 1);

一行搞定,結果自動封裝成 News 物件。同樣的功能用原生寫法起碼要二十行。

find() 的第一個參數是泛型類別——傳入什麼類別,回傳就是什麼型別;第二個參數是 id 值。

取第一條與最後一條

News firstNews = DataSupport.findFirst(News.class);
News lastNews  = DataSupport.findLast(News.class);

傳統做法得在 SQL 裡指定 limit 再取第一筆,LitePal 直接提供了語意明確的方法。

查詢多筆

想把 id 為 1、3、5、7 的資料一次取出:

List<News> newsList = DataSupport.findAll(News.class, 1, 3, 5, 7);

後面可以傳入任意個 id。若這些 id 已經在陣列裡:

long[] ids = new long[]{ 1, 3, 5, 7 };
List<News> newsList = DataSupport.findAll(News.class, ids);

而如果不指定任何 id,就是查詢整張表:

List<News> allNews = DataSupport.findAll(News.class);

值得留意的是,上面這幾種寫法其實呼叫的是同一個方法重載,靠可變參數達成多樣效果,語意卻依然清楚——這就是所謂的「查詢藝術」。

連綴查詢

前面的用法都只能按 id 查詢。要自訂條件,LitePal 用連綴(chained calls)解決。

查詢評論數大於零的新聞:

List<News> newsList = DataSupport.where("commentcount > ?", 0).find(News.class);

等價的 SQL:

select * from news where commentcount > 0;

where() 的第一個參數是條件式,其後所有參數用來替換占位符。

只要 title 與 content 兩欄,再加上 select():

List<News> newsList = DataSupport.select("title", "content")
        .where("commentcount > ?", 0)
        .find(News.class);
select title, content from news where commentcount > 0;

按發布時間倒序排列,加上 order():

List<News> newsList = DataSupport.select("title", "content")
        .where("commentcount > ?", 0)
        .order("publishdate desc")
        .find(News.class);
select title, content from news where commentcount > 0 order by publishdate desc;

asc 為正序,desc 為倒序。

只取前 10 筆,加上 limit():

List<News> newsList = DataSupport.select("title", "content")
        .where("commentcount > ?", 0)
        .order("publishdate desc")
        .limit(10)
        .find(News.class);

分頁時,第二頁要取第 11 到 20 筆,再加上 offset():

List<News> newsList = DataSupport.select("title", "content")
        .where("commentcount > ?", 0)
        .order("publishdate desc")
        .limit(10)
        .offset(10)
        .find(News.class);
select title, content from news where commentcount > 0 order by publishdate desc limit 10, 10;

對比 query() 那串即使不用也得填 null 的參數,連綴查詢的優勢很明顯:需要什麼就接什麼,不需要的直接不寫。

激進查詢(Eager)

LitePal 預設是「懶查詢」——不會順帶把關聯表的資料一起抓回來,這也是官方推薦的做法。若你確實想一次取回關聯資料,每個 find() 都有一個帶 isEager 參數的重載:

News news = DataSupport.find(News.class, 1, true);
List<Comment> commentList = news.getCommentList();

寫法上只是在最後多帶一個 true。由於 comment 與 news 是多對一關聯,查一筆新聞時對應的評論也會一起被取出。

但這種方式官方並不推薦,原因有二:關聯表資料量大時查詢會很慢;而且無法繼續迭代——查不到「關聯表的關聯表」。

更好的做法是在模型類別中補一個方法,把查詢延後到真正需要時:

public class News extends DataSupport {

    // ...

    public List<Comment> getComments() {
        return DataSupport.where("news_id = ?", String.valueOf(id))
                          .find(Comment.class);
    }
}

這樣在需要評論時才呼叫 getComments(),既省資源也更好控制。

原生查詢

總會遇到連 API 也覆蓋不到的奇怪需求。LitePal 保留了逃生口 findBySQL():

Cursor cursor = DataSupport.findBySQL(
        "select * from news where commentcount > ?", "0");

第一個參數是 SQL 語句,其後參數用於替換占位符,回傳 Cursor——與原生寫法一致。

三、小結

LitePal 的查詢設計可以濃縮成三句話:

  1. 單筆用 find(),多筆用 findAll(),兩端各有一對語意明確的輔助方法。
  2. 條件複雜時改用連綴:select → where → order → limit → offset,用多少接多少。
  3. 關聯資料優先懶載入,在模型類別中補查詢方法,而不是依賴激進查詢。

下一篇將開始講解聚合函數的用法。

LitePal 開源專案位址

https://github.com/LitePalFramework/LitePal

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved